本文内容
@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();

本文详细介绍了Spring框架中`@Value`, `@Resource`, `@PostConstruct`和`@PreDestroy`注解的使用,包括基本用法、区别以及各种使用场景,如注入配置属性、处理无法解析的属性值、提供默认值、支持SpEL表达式等。同时,文章还展示了如何通过这些注解实现bean的生命周期回调。"
132876391,18158630,MATLAB中归零非删余Turbo码的参数分析,"['通信技术', '编码理论', 'MATLAB编程', '数据传输', '无线通信']
最低0.47元/天 解锁文章
2万+

被折叠的 条评论
为什么被折叠?



