IoC容器篇(九)——基于注解的容器配置(二)

目录

基于注解的容器配置

5.使用泛型作为自动装配修饰语

6.CustomAutowireConfigure

7.@Resource

8.@PostConstruct and @PreDestory

翻译源:Spring官方文档


基于注解的容器配置

 

5.使用泛型作为自动装配修饰语

@Autowired
private Store<String> s1; // <String> qualifier, injects the stringStore bean

@Autowired
private Store<Integer> s2; // <Integer> qualifier, injects the integerStore bean

note:Store是泛型接口,使用不同类型实现的bean进行注入。

ps:除了使用@Qualifier注解,泛型的类型也可以用于确认注入的依赖bean。

 

6.CustomAutowireConfigure

<bean id="customAutowireConfigurer"
        class="org.springframework.beans.factory.annotation.CustomAutowireConfigurer">
    <property name="customQualifierTypes">
        <set>
            <value>example.CustomQualifier</value>
        </set>
    </property>
</bean>

ps:CustomAutowireConfigure是一个BeanFactoryPostProcessor的实现,用于注册自制的修饰符注解类型,即使这些注解类型没有使用@Qualifier进行注解。

 

AutowireCandidateResolver决定自动装配候选的依据:

  • 每一个bean定义的autowire-candidate值
  • 任何<beans/>元素上可能的default-autowire-candidates模式
  • @Qualifier注解以及注册在CustomAutowireConfigurer上的自定义注解

 

7.@Resource

public class Example {

    private Foo foo;

    @Resource(name="foo")
    public void setFoo(Foo foo) {
        this.foo = foo;
    } 
}

note:将名为foo的bean通过Example的setter方法注入。

ps:如果没有显式为@Resource注解指定值,那么注入时使用的默认bean名称为域名或属性名。

ps:不使用显示名称的@Resource与@Autowire类似,即查找使用基本类型匹配而不是特定名称bean,以及解析well-known可解析依赖:BeanFactory、ApplicationContext、ResourceLoader、ApplicationEventPublisher、MessageSource。

 

public class Example {

    @Resource
    private Foo foo;

    @Resource
    private ApplicationContext context;
    
}

note:foo域首先查找名为foo的域,然后退步查找类型匹配Foo的bean。

note:context被可解析依赖类型ApplicationContext注入。

 

由注解提供的名称,通过被CommonAnnotationBeanPostProcessor意识到的ApplicationContext被解析为一个bean名称。

如果显式配置了Spring的SimpleJndiBeanFactory,那么名称便可以被解析。

不过,推荐依赖默认行为与简单使用JNDI查找能力去保持间接水平。

 

8.@PostConstruct and @PreDestory

public class Example {

    @PostConstruct
    public void actionA() {

    }

    @PreDestroy
    public void actionB() {

    }
}

note:actionA()设置为initialization 回掉方法。

note:actionB()设置为destruction回调方法。

 

 


翻译源:Spring官方文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值