@Autowired注解的用法:可以用于构造器,方法,参数,字段进行属性注入,有一个required属性,默认是true,当改成false时,如果注入的属性在容器中不存在也不会报错
@Resource该注解来源于javax包,有个属性name可以指定注入哪一个bean,当容器中某个类存在2个bean时,该注解就非常有用了,但没有required属性
@Qualifier和@Autowired搭配使用,可以实现@Resource指定注入某个bean的功能,当某个类存在2个bean时,这样也是一种解决方案
@Primary 代表优先使用某个类,例如UserDAO向spring注入2个bean,dao1,和dao2;如果注入dao1时加了@Primary 注解,则,其他类注入UserDAO会优先注入dao1
@Inject 作用跟@Autowired相同,但他没有required属性,并且需要依赖第三方包
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
好处是,应用不依赖spring
public class UserDAO {
private String id="1"; public String getId() {
return id;
} public void setId(String id) {
this.id = id;
}
}
@Configuration
@Import({UserService.class})
public class AppConfigurate {
@Bean("userDAO1")
public UserDAO userDAO(){
UserDAO userDAO = new UserDAO();
userDAO.setId("userDAO1");
return userDAO;
}
@Bean("userDAO2")
public UserDAO userDAO2(){
UserDAO userDAO = new UserDAO();
userDAO.setId("userDAO2");
return userDAO;
}
}
public class UserService {
@Autowired
private UserDAO userDAO; public void sayHi(){
System.out.println(userDAO.getId());
} }
public class APP {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfigurate.class);
UserService userService =(UserService) ctx.getBean("com.yang.xiao.config.UserService");
userService.sayHi();
String[] beanDefinitionNames = ctx.getBeanDefinitionNames();
for (String definitionName : beanDefinitionNames) {
System.out.println(definitionName);
} }
}
上面代码直接使用@Autowired注入UserDAO,执行后会报错,因为spring区分不了要注入哪个bean;解决方案如下:
//1.Autowired注入的属性优先按照名字去匹配,名字匹配不到才会按照类型去匹配
public class UserService {
@Autowired
private UserDAO userDAO1; public void sayHi(){
System.out.println(userDAO1.getId());
} }
//2.@Qualifier("userDAO2") 使用该注解去指定
public class UserService {
@Autowired
@Qualifier("userDAO2")
private UserDAO userDAO; public void sayHi(){
System.out.println(userDAO.getId());
} }
//3.使用@Primary去指定优先级
@Configuration
@Import({UserService.class})
public class AppConfigurate {
@Bean("userDAO1")
@Primary
public UserDAO userDAO(){
UserDAO userDAO = new UserDAO();
userDAO.setId("userDAO1");
return userDAO;
}
@Bean("userDAO2")
public UserDAO userDAO2(){
UserDAO userDAO = new UserDAO();
userDAO.setId("userDAO2");
return userDAO;
}
}
//4.使用@Resource注解
public class UserService {
@Resource(name = "userDAO2")
private UserDAO userDAO; public void sayHi(){
System.out.println(userDAO.getId());
} }
//@Inject注解用法
public class UserService {
@Inject
private UserDAO userDAO; public void sayHi(){
System.out.println(userDAO.getId());
} }