简体   繁体   中英

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) . 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

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

and I like pass it to my bean constructor. Is there way to add this custom logic before bean autowired ? 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). Is there any example of this ? Or maybe I need to use my custom annotation instead autowired and use 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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