基于注解的自动装配,来看看几个注解的源码和基本的使用
@Autowired&@Qualifier&@Primary
@Autowired
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
boolean required() default true;// 自动装配默认一定要将属性赋值好,没有就会报错;
}
从源码可以看出:
- @Autowired可以标记在方法上,方法参数上,构造方法上,属性上
- 如果我要注入的属性在spring容器没有找到,默认required()是true,就是一定要注入,但是如果没有在容器找到的话就会报错,如果设置成false,如果找不到就注入为null
使用:
首先创建一个dao吧,并放入spring容器中
@Repository
public class PersonDao {
}
使用@Autowired,标记在字段上,切记在此之前要扫描包。不同于springboot的包自动扫描机制
@Autowired
private PersonDao personDao;
//@Conditional(value = {WinCondition.class})
@Bean(name = "getPerson1")
public Person getPerson(){
System.out.println("创建对象1");
System.out.println("*******"+personDao);
return new Person("kevin1",21);
}
测试:
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
System.out.println("ioc容器启动");
Person person1 = (Person) applicationContext.getBean("getPerson1");
System.out.println(person1);
结果:
创建对象1
*******main.java.dao.PersonDao@2bbaf4f0
该注解默认优先按照类型去容器中找对应的组件,如果找到多个相同类型的组件,再将属性的名称作为组件的id去容器中查找
在加多一个同类的bean放入容器中
@Bean
public PersonDao personDao1(){
PersonDao personDao = new PersonDao();
personDao.setI(2);
return personDao;
}
修改下原来persondao
@Repository
public class PersonDao {
// 标识,看调用哪个bean
private int i = 1 ;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
结果:
创建对象1
*******1
现在有两个相同类型的bean在容器中,@Autowired注解会先按照类型去找,结果找到了这两个bean,接着会优先以personDao属性名去匹配,相当于:applicationContext.getBean("personDao")
如果我们想按照名称在容器中找,可以使用@Qualifier指定需要装配的组件的id,而不是使用属性名,需要和@Autowired配合使用
@Autowired
@Qualifier("personDao1")
private PersonDao personDao;
现在便可以拿到2
创建对象1
*******2
还可以使用spring提供的一个解决这个自动装配的问题
@Primary:让Spring进行自动装配的时候,默认使用首选的bean
比如,我现在想装配时首选装配personDao2
@Primary //首选装配
@Bean(name = "personDao1")
public PersonDao personDao1(){
PersonDao personDao = new PersonDao();
personDao.setI(2);
return personDao;
}
原来的@Qualifier("personDao1")
注释掉
补充:
@Autowired:构造器,参数,方法,属性;都是从容器中获取参数组件的值
1)、[标注在方法位置]:@Bean+方法参数;参数从容器中获取;默认不写@Autowired效果是一样的;都能自动装配
2)、[标在构造器上]:如果组件只有一个有参构造器,这个有参构造器的@Autowired可以省略,参数位置的组件还是可以自动从容器中获取
3)、放在参数位置:
@Resource&@Inject
这两个是java规范提供的注解
@Resource:
1.可以和@Autowired一样实现自动装配功能;默认是按照组件名称进行装配的,相当==@Autowired+ @Qualifier(“name”);
2.没有能支持@Primary功能没有支持@Autowired(reqiured=false);
@Inject:
1.需要导入javax.inject的包,和Autowired的功能一样。没有required=false的功能;