-
spring依赖注入
spring的控制翻转和依赖注入在某种情况下是等同的概念,控制翻转是通过依赖注入实现的。依赖注入是指容器负责创建对象和维护对象间的依赖关系,而不是通过对象本身负责自己的创建和解决自己的依赖。
spring IOC容器(ApplicationContext)负责创建Bean,并通过容器将功能类Bean注入到所需要的Bean中。Spring提供了xml、注解和java配置的方式来实现Bean的创建和注入。无论你采用何种配置,都被称为配置元数据,所谓元数据就是描述数据的数据。
-
使用注解方式注入
注入bean的注解,一般情况下使用:
@Autowired、@Inject和@Resoure,这里三种注解是等价的。注解注入很简单,直接上代码:
@Service
public class AdService {
@Autowired //将AdMapper Bean注入到AdService中
private AdMapper adMapper;
}
-
使用java配置依赖注入
java配置是通过使用@Configuration和@Bean注解来实现的:
@Configuration声明当前类是一个配置类,相当于一个spring配置的xml文件;
@Bean使用在方法上,声明当前方法的返回值是一个bean,即相当于xml文件中的一个bean标签配置。
-
bean
public class AdService {
public String beanTest() throws Exception {
return "Hello World!";
}
}
-
另一个bean
public class GeAdService {
private AdService adServicer;//不使用@Autowired注解注入
public void setAdService(AdService adService){//调用第一个bean
this.adService = adService;
}
public void sayHello(){
adService.beanTest();
}
}
这里的AdService和GeAdService没有使用任何注解,只是一个单纯的java类,所有的注入配置都交给统一配置类来完成。
-
统一配置类
@Configuration//表示该类是一个配置类
public class DemoConfig {
@Bean//声明bean
public AdServicer adServicer(){
return new AdServicer();
}
@Bean//声明bean
public GeAdService geAdService (){
GeAdService geAdService = new GeAdService();
geAdService.setAdService(adServicer());//注入AdServicer Bean
return geAdService;
}
}