使对象弹簧管理 [英] Make object spring managed

查看:195
本文介绍了使对象弹簧管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何管理已存在的对象弹簧?我想使用<$ c $将其连接到 Springs AoP 功能C> AspectJ的。我知道这是一个挑战,因为 Spring AoP 使用可能与对象一起创建的动态代理。

How can I get an already existing object spring managed? I would like to hook it up to Springs AoP capabilities using aspectj. I know this to be a challenge since Spring AoP uses dynamic proxies which probably are created along with the object.

我有一个第三方类它接受一个只在运行时中知道的构造函数参数,
因此我似乎无法将它添加到我的 applicationContext 或使用spring FactoryBean 构造界面。 还有其他方法吗?

I have a third-party class which takes a constructor argument which is only known in runtime, hence it seems I cannot add it to my applicationContext or use springs FactoryBean interface for construction. Is there any other way?

我已经尝试过以下方法但没有取得太大成功:

I've already tried the following without great success:

Obj obj = new ThirdPartyObj("runtime constructor arg");
appContext.getAutowireCapableBeanFactory().initializeBean(obj, "Obj");

可能是春季管理的,但我仍然无法使用它触发方面。

It might be spring-managed, but I still cannot use it to trigger aspects.

axtavt 指出问题是我不使用从 initializeBean(..)返回的对象。两种提到的方法都有效,但仅限于:

axtavt pointed out the problem is that I don't use the object returned from initializeBean(..). Both mentioned approaches work, but only if:


  • 使用接口 ObjInterface obj =(ObjInterface)ac。 getBean(obj,args); 或者我们将获得:

java.lang.ClassCastException:$ Proxy28无法强制转换为com.company.Obj

不使用接口但启用 CGLIB 。这需要非私有默认构造函数,否则我们将得到:

Not using interface but enable CGLIB. This requires a non-private default constructor, or we will get a:

java.lang.IllegalArgumentException:Superclass没有空构造函数但没有给出参数

推荐答案

您应该能够使用此方法触发方面(请注意,您需要使用可以作为代理的返回对象):

You should be able to trigger aspects using this (note that you need to use returned object which can be a proxy):

Obj obj = new ThirdPartyObj("runtime constructor arg");     
obj = appContext.getAutowireCapableBeanFactory().initializeBean(obj, "Obj"); 

另一种选择是将其声明为常规bean并通过 getBean():

Another option is to declare it as a regular bean and pass the constructor argument via getBean():

Obj obj = appContext.getBean("Obj", "runtime constructor arg");     

这篇关于使对象弹簧管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆