您的位置:首页 > 编程语言 > Java开发

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

2017-06-09 18:03 1506 查看
该问题指在不在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.instru
4000
ment.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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐