Spring还支持使用@Resource(JSR250)和@Inject(JSR330)[java规范的注解]
一、@Resource:
可以和@Autowired一样实现自动装配功能;默认是按照组件名称进行装配的。
不能支持@Primary功能,不能支持@Autowired(reqiured=false)。
1、BookDao
@Repository
public class BookDao {
private String lable = "1";
public String getLable() {
return lable;
}
public void setLable(String lable) {
this.lable = lable;
}
@Override
public String toString() {
return "BookDao [lable=" + lable + "]";
}
}
2、MainConifgOfAutowired
@Configuration
@ComponentScan({"com.atguigu.service","com.atguigu.dao"})
public class MainConifgOfAutowired {
@Primary
@Bean("bookDao2")
public BookDao bookDao(){
BookDao bookDao = new BookDao();
bookDao.setLable("2");
return bookDao;
}
}
3、BookService
@Service
public class BookService {
@Resource
private BookDao bookDao;
@Override
public String toString() {
return "BookService{" +
"bookDao=" + bookDao +
'}';
}
}
测试:
@Test
public void test01(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConifgOfAutowired.class);
BookService bookService = applicationContext.getBean(BookService.class);
System.out.println(bookService);
BookDao bean = applicationContext.getBean(BookDao.class);
System.out.println(bean);
applicationContext.close();
}
修改BookService,使用@Resource(name = “bookDao2”)指定bean的名称
@Service
public class BookService {
@Resource(name = "bookDao2")
private BookDao bookDao;
@Override
public String toString() {
return "BookService{" +
"bookDao=" + bookDao +
'}';
}
}
二、@Inject:
需要导入javax.inject的包,和Autowired的功能一样。没有属性,不能支持required=false的功能。
1、引入依赖
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
2、修改BookService使用 @Inject 注解
@Service
public class BookService {
@Inject
private BookDao bookDao;
@Override
public String toString() {
return "BookService{" +
"bookDao=" + bookDao +
'}';
}
}
@Autowired:Spring定义的; @Resource、@Inject都是java规范。
AutowiredAnnotationBeanPostProcessor:解析完成自动装配功能。