简体   繁体   English

注入具有带有通用类参数的构造函数的通用bean的方法

[英]Way to inject generic bean that have constructor with generic class argument

I have generic class ObjectDaoReflect<T extends BaseEntity> it work with reflaction, because of type erasure it have constructor with generic class parameter public ObjectDaoReflect(Class<T> objectClass) . 我有通用类ObjectDaoReflect<T extends BaseEntity> extended ObjectDaoReflect<T extends BaseEntity>它可以进行反射,因为类型擦除它具有带有通用类参数public ObjectDaoReflect(Class<T> objectClass)构造函数。 My idea is add custom logic before bean instancing by spring (its prototype bean), and read generic information about Field in which spring is going to inject my bean, using this code I can read genereic field class 我的想法是在spring实例化bean(其原型bean)之前添加自定义逻辑,并读取有关Spring将在其中注入我的bean的Field的一般信息,使用此代码,我可以读取一般字段类

(Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]

and I like pass it to my bean constructor. 而且我喜欢将其传递给我的bean构造函数。 Is there way to add this custom logic before bean autowired ? 有没有办法在bean自动装配之前添加此自定义逻辑? In general I need read field in what spring is going to inject my bean, read its generic type and pass it to my bean constructor (or setter). 通常,我需要在哪个春天将要注入我的bean的地方读取字段,读取它的泛型类型并将其传递给我的bean构造函数(或setter)。 Is there any example of this ? 有这个例子吗? Or maybe I need to use my custom annotation instead autowired and use BeanPostProcessor postProcessBeforeInitialization ? 还是我需要使用自定义批注而不是自动装配并使用BeanPostProcessor postProcessBeforeInitialization?

You can try something like this: 您可以尝试如下操作:

<bean id="blaBean" class="bla.bla.BlaBeanImpl">
         <constructor-arg type="java.lang.Class" value="#{(CheckClassUtil.shouldUseFoo()) ? 'bla.bla.Foo' : 'bla.bla.Bar'}"/>
   </bean>

use your logic in EL for choosing constructor argument as class. 在EL中使用您的逻辑选择构造函数参数作为类。 You might create static method that return class name as a String and call it through EL to set 'value' parameter of constructor-arg element. 您可能会创建静态方法,该方法将类名称返回为String并通过EL调用它以设置构造函数arg元素的“值”参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM