关于非Spring管理下的Bean通过反射在newInstance()下的自动注入问题

来源:互联网 发布:淘宝店铺监管会怎么样 编辑:程序博客网 时间:2024/06/05 06:32

该问题指在不在Spring管理下的bean,通过new创建一个对象让spring来完成依赖注入。

问题起因:
最近在一个Spring项目中使用了第三方开源项目,其中有一个配置,直接抓取类名通过反射去初始化对象
这里写图片描述

在自己实现的cache对象里,需要往对象里注入一个配置好的redisTemplate 这里写图片描述
在spring自动扫描下配置了@Resource,在Controller里注入此缓存类,redisTemplate是被成功注入进来的,但是实际情况是需要new这个缓存类,来存储信息。

查阅官方文档
这里写图片描述
在Spring容器之外创建的对象,
可以通过@Configurable来标记让spring知道这个Bean在创建时需要注入依赖

关于@Configurable的使用方式:
如果仅在类名上标识注解,需要在spring的配置文件里添加这个bean

<bean class="com.xyz.myapp.domain.Account" scope="prototype">    <property name="fundsTransferService" ref="fundsTransferService"/></bean>

这样的好处是省掉了id

@Configurable(“account”)
这样配置表示将去寻找名为”account”的bean定义

当然也可以直接使用@Configurable配合@Resource来免除xml配置

@Configurable内参数
autowire=Autowire.BY_TYPE ;autowire=Autowire.BY_NAME
按类型或按名称进行装配
dependencyCheck
是否进行依赖检查
preConstruction
如果不配置为true,依赖将在bean被初始化后添加依赖,反之在构造函数执行之前注入依赖


想要注解生效:
需要load-time weaving,在加载时注入依赖。

<context:load-time-weaver weaver-class="org.springframework.instrument.classloading.ReflectiveLoadTimeWeaver" aspectj-weaving="on"/>

关于context:load-time-weaver的解释,官方文档是这样说的

Once configured for the ApplicationContext. Any bean within that ApplicationContext may implement LoadTimeWeaverAware, thereby receiving a reference to the load-time weaver instance. This is particularly useful in combination with Spring’s JPA support where load-time weaving may be necessary for JPA class transformation.

阅读全文
1 0