在spring xml配置中使用应用程序常量的最佳方法是什么?

ric*_*nal 12 java spring constants spring-el

我想在spring xml配置中使用我的应用程序常量.

我知道用Spring SpEl这样做是这样的:

<bean class="example.SomeBean">
    <property name="anyProperty" value="#{ T(example.AppConfiguration).EXAMPLE_CONSTANT}" />
    <!-- Other config -->
</bean>
Run Code Online (Sandbox Code Playgroud)

那么,有更好的方法吗?

ska*_*man 29

您可以使用<util:constant>(参见C.2.2 util模式):

<bean class="example.SomeBean">
    <property name="anyProperty">
       <util:constant static-field="example.AppConfiguration.EXAMPLE_CONSTANT" />
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

然而,关于这是否更好,这是值得商榷的.您的SpEL版本更简洁.

另一种选择是使用Java配置样式,这更自然(参见4.12基于Java的容器配置):

@Bean
public SomeBean myBean() {
    SomeBean bean = new SomeBean();
    bean.setProperty(EXAMPLE_CONSTANT);  // using a static import
    return bean;
}
Run Code Online (Sandbox Code Playgroud)