一、Required
用于修饰属性的setter方法,表示该属性必须被配置初始化,否则抛出BeanInitializationException 异常。
public class Student{
private int age;
@Required
public void setAge(int age){
this.age = age;
}
}
二、Autowired
Spring配置方式有两种种:xml、java config。
java config中使用最为频繁的是Autowired注解,字面意思是自动装配,在Spring中是指将Sring容器中的bean自动的和需要这个bean的类组装在一起。
Autowired可以修饰属性、方法等等。将 @Autowired 注释添加到需要该类型数组的字段或方法,则 Spring 会从 ApplicationContext 中搜寻符合指定类型的所有 bean
public class SimpleMovieLister{
@Autowired
private MovieFinder movieFinder;
@Autowired
public void setMovieFinder(MovieFinder movieFinder){
this.movieFinder = movieFinder
}
@Autowired
public void prepare(MovieCatalog movieCatalog,
CustomerPreferenceDao customerPreferenceDao) {
this.movieCatalog = movieCatalog;
this.customerPreferenceDao = customerPreferenceDao;
}
}
三、Qualifier
与Autowired结合使用,指定具体地用于自动装配的bean。如下:装配student1
public class Profile {
@Autowired
@Qualifier("student1")
private Student student;
public Profile(){
System.out.println("Inside Profile constructor." );
}
public void printAge() {
System.out.println("Age : " + student.getAge() );
}
public void printName() {
System.out.println("Name : " + student.getName() );
}
}