在本文中,我们将学习如何在 Spring Applications 中使用基于构造函数的依赖注入。
我们可以使用基于 Spring Annotation 的容器配置或基于 Spring Java 的容器配置或两者的组合来演示此示例
基于构造函数的 DI 是通过容器调用具有多个参数的构造函数来完成的,每个参数代表一个依赖项。
在下图中,突出显示的代码显示了一个基于构造函数的依赖注入示例。
让我们使用带有 @Configuration 注解的 java 类 AppConfiguration
创建一个 spring 配置文件。这相当于没有bean定义的spring XML配置文件。
package com.javadevsguide.springframework.di.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.javadevsguide.springframework.di")
public class AppConfiguration {
}
现在创建一个 MessageService
接口并为其提供两个以上的实现。
public interface MessageService {
public void sendMsg(String message);
}
让我们实现 MessageService
接口。有很多方法可以发送消息,例如通过电子邮件、短信、推特等。
@Service("EmailService")
public class EmailService implements MessageService{
public void sendMsg(String message) {
System.out.println(message);
}
}
@Service("SMSService")
public class SMSService implements MessageService{
public void sendMsg(String message) {
System.out.println(message);
}
}
@Service("TwitterService")
public class TwitterService implements MessageService{
public void sendMsg(String message) {
System.out.println(message);
}
}
请注意,MessageService
接口有多种实现,因此为避免歧义,我们使用@Qualifier 注解。是时候演示基于构造函数的依赖注入的用法了。为避免解耦,请始终使用接口或抽象基类作为实例变量和构造函数参数。在本例中,我们使用了 MessageService 接口。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.javadevsguide.springframework.di.service.MessageService;
@Component
public class ConstructorBasedInjection {
private MessageService messageService;
@Autowired
public ConstructorBasedInjection(@Qualifier("TwitterService")
MessageService messageService) {
super();
this.messageService = messageService;
}
public void processMsg(String message) {
messageService.sendMsg(message);
}
}
是时候测试基于构造函数的依赖注入的使用了。让我们创建一个作为 ApplicationContext
对象的 IOC 容器对象并从中获取 bean。
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.javadevsguide.springframework.di.config.AppConfiguration;
import com.javadevsguide.springframework.di.constructor.ConstructorBasedInjection;
public class Application {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfiguration.class);
ConstructorBasedInjection constructorBasedInjection =applicationContext.getBean(ConstructorBasedInjection.class);
constructorBasedInjection.processMsg("twitter message sending ");
}
}
请注意,我们使用带有 @Configuration 注释的 AppConfiguration
类进行配置。
在本文中,我们通过构造函数演示了 spring 依赖注入。这篇文章的源代码可以在我的 GitHub 上找到——这是一个基于 Eclipse 的项目,所以它应该很容易导入和运行。
Github 存储库:Spring Dependency Injection via Constructor Example
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/06/spring-dependency-injection-via.html
内容来源于网络,如有侵权,请联系作者删除!