【问题标题】:Spring @Value annotation not workingSpring @Value 注释不起作用
【发布时间】:2014-03-26 20:24:53
【问题描述】:

没有在我的 bean 上设置带有 @Value 注释的属性。

我的上下文和类位于另一个项目的类路径上的 jar 中。它的 spring 上下文导入我的 spring 上下文,我的 spring 上下文从类路径加载配置文件并包含各种 bean 定义。

没有在任何地方使用延迟加载,我的 jar 使用的是 Spring 3.1.4,而使用我的 jar 的项目使用的是 Spring 3.2.3。

显示属性文件的记录器在外部项目加载其上下文(导入我的)时加载

[main] INFO  Loading properties file from class path resource [connector-config.properties] - (PropertyPlaceholderConfigurer.java:172:)

摘自我的 Spring 上下文:

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
    lazy-init="false">
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="ignoreResourceNotFound" value="true" />
    <property name="locations">
        <list>
            <value>classpath:connector-config.properties</value>
        </list>
    </property>
</bean>
...
    <!-- The actual beans referenced are not foo bar and com but should not be relevant to this issue -->
<bean id="requestGenerator" class="com.connector.RequestGenerator">
    <constructor-arg name="foo" ref="foo" />
    <constructor-arg name="bar" ref="bar" />
    <constructor-arg name="com" ref="com" />
</bean>

使用我的 jar 位于项目类路径中的配置文件

ruleType=PAUL
response.poolSize=10
ack.poolSize=10
#This needs to be in minutes
max.run.time=100
base.dir=\\

来自外部项目的类从我的上下文中加载一个 bean: 通过在 Eclipse 调试模式下检查 requestGen 对象,我可以看到属性 ruleType 为 null。 鉴于上述属性文件,ruleType 应为“PAUL”但它为 null。

public class App
{
public static void main(Straing[] args)
{
    @SuppressWarnings("resource")
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-context.xml");
    RequestGenerator requestGen = context.getBean("requestGenerator", RequestGenerator.class);

【问题讨论】:

  • 你会发布 RequestGenerator 吗?您期望设置什么值
  • 贴出RequestGenerator的相关部分和属性文件
  • 向我们展示 bean 配置的其余部分,特别是 requestGenerator bean 定义。
  • 您所展示的一切似乎都表明您所描述的行为。告诉我们您在哪里看到字段ruleTypenull。你有NPE吗?向我们展示堆栈跟踪?
  • 我的错,让我修正一下我的帖子。感谢您迄今为止的所有帮助。

标签: java spring


【解决方案1】:

@Value 注释由 AutowiredAnnotationBeanPostProcessor 处理,如果您在 XML 中(或直接使用 bean 定义)有 &lt;component-scan&gt;&lt;annotation-config&gt; 配置,则通常会注册该注释。您需要添加其中任何一个,可能是 &lt;annotation-config&gt;,因为您说过您没有任何 @Component 类。

【讨论】:

  • 谢谢,问题是缺少 。从树上看不到森林。
【解决方案2】:

自 Spring 3.1 起,不建议使用 PropertyPlaceholderConfigurer 来执行此类任务。欲了解更多信息,请参阅其JavaDoc

请出示您的connector-config.propertiesRequestGenerator 的代码以获取有关问题的更多信息。

【讨论】:

  • 这个解决方案实际上对我有用,而不是公认的答案。就我而言,我有一些较旧的 Spring 配置,它们定义了 PropertyPlaceholderConfigurer。一旦我删除了这些引用,一切都按照记录进行。
猜你喜欢
  • 2018-03-03
  • 2014-08-14
  • 2015-10-26
  • 2016-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
相关资源
最近更新 更多