本文内容
@Resource
实现依赖注入@Value
详细使用@PostConstruct
@PreDestroy
的使用
@Resource
实现依赖注入
前面章节介绍了使用@Autowired
注入依赖的详细用法,感兴趣的可以翻看前面的文章。Spring 还支持通过在字段或 bean 的Setter
方法上使用 JSR-250 @Resource
注解进行注入。
@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
public @interface Resource {
// 指定名称
String name() default "";
}
基本使用
依赖组件定义
@Component
public class RepositoryA implements RepositoryBase {
}
@Component
public class RepositoryB implements RepositoryBase {
}
使用@Resource
注入依赖
@Component
public class Service1 {
// 字段
@Resource
private RepositoryA repositoryA;
private RepositoryB repositoryB;
// Setter方法
@Resource
public void setRepositoryB(RepositoryB repositoryB) {
this.repositoryB = repositoryB;
}
// ...
}
运行测试
@org.junit.Test
public void test() {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
Service1 service1 = context.getBean(Service1.class);
System.out.println(service1);
context.close();
}
// 结果
Service1{repositoryA=com.crab.spring.ioc.d