pass “HardCoded” Constructor Arg Class<T> to bean via Spring Config

落爺英雄遲暮 提交于 2020-01-02 03:44:17

问题


I have a generic type that I am injecting into a service. Because of the way generics are implemented in Java, I need to have a constructor arg (or property setter) that holds the Class information of the generic type parameter.

My question is -- Can I, via property injection or specifying a constructor arg, pass in an instance of Class with spring?

I DO know the type of T before run time so I know specifically what the Type parameter will be.

I was thinking it would look something like this:

<bean id="dataMartService" class="com.someclass">
    <constructor-arg value="java.lang.class<com.someotherclass>" />
</bean>

Am I completely off in how this should happen?


回答1:


Try:

<bean id="dataMartService" class="com.someClass">
    <constructor-arg>
        <value type="java.lang.Class">someotherclass</value>
    </constructor-arg>
</bean>



回答2:


Use spring el:

<constructor-arg value="#{ T(java.lang.Math) }" />

(you'll need spring 3.0 for this)

That being said, if you pass a string into an argument where a class is expected during a property set, spring should automatically convert it, though i'm not sure how this works when matching constructors. The above approach is much more concise.




回答3:


You can use:

//for constructor
public CheckSpell(SpellCheker spellCheker){
         this.spellCheker=spellCheker;
}

//Use object reference as bean

    <bean id="textEditor" class="com.sring.spellCheck">
          <constructor-arg ref="spellChecker"/>
      </bean>

<bean id="spellCheker" class="com.spring.SpellCheker"/>


来源:https://stackoverflow.com/questions/11971651/pass-hardcoded-constructor-arg-classt-to-bean-via-spring-config

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!