Spring系列12: `@Value` `@Resource` `@PostConstruct` `@PreDestroy` 详解

本文内容

  1. @Resource实现依赖注入
  2. @Value详细使用
  3. @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
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值