开发者

Possible to access java variable in ApplicationContext.xml?

开发者 https://www.devze.com 2023-02-21 01:50 出处:网络
We\'re using the Springframework. Is it possible to access an e开发者_Go百科xisting variable from a java class in ApplicationContext.xml?

We're using the Springframework. Is it possible to access an e开发者_Go百科xisting variable from a java class in ApplicationContext.xml?

For instance, we have a class with a threadnumber which is initialized on 5. Is there a way to read that '5' in the applicationcontext, so we can use it to inject other Java classes?

If yes, how?

Kind regards,

Walle


If you are using Spring 3, you should be able to do it using Spring EL. Check out http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/expressions.html

Here is an example assuming you want to use a public static field THREAD_NUMBER of class mypackage.MyClass:

  <bean id="myBean"
        class="mypackage.AnotherClass">
    <property name="theProperty">
      <value>#{T(mypackage.MyClass).THREAD_NUMBER}</value>
    </property>
  </bean>

If it's not a static field but an instance field you would need a bean first and then call an apropriate getter from Spring EL expression.


If you dont want to use EL or using an older version of Spring,

<bean id="myBean" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
        <property name="staticField" value="MyClass.MY_STATIC_FIELD"/> </bean>


Take a look at BeanPostProcessor. It could probably do what you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号