【问题标题】:Spring @Value annotations don't work, returning nullSpring @Value 注解不起作用,返回 null
【发布时间】:2015-05-07 06:14:49
【问题描述】:

我有以下课程:

@Component
public class MyClass {

@Value("${main.url}") private String mainUrl;

以下 XML 上下文:

<context:annotation-config/>
  <context:component-scan base-package="mypackage"/>

  <context:property-placeholder file-encoding="UTF-8" location="classpath:/app.properties" ignore-unresolvable="true"/>

和道具文件:

main.url=veryniceurl.com

注入不起作用,它始终为空。 我读了很多类似的例子,我认为一切都很好,但事实并非如此。如果我忘记了什么,谁能告诉我?我正在使用 Mule ESB。

【问题讨论】:

  • app.properties 在你的类路径的根目录中吗?您应该尝试将 ignore-unresolvable 设置为 false 以查看 Spring 是否抱怨。

标签: java spring annotations mule


【解决方案1】:

@Value doesn't seem to work with Mule。相反,您需要通过 Mule XML 将其连接起来,我假设您将组件作为 Spring Bean 加载:

<spring:bean id="MyClass" class="com.example.MyClass">
   <spring:property name="mainUrl" value="${main.url}"/>
</spring:bean>

【讨论】:

    【解决方案2】:

    为您的属性提供一个 id 并使用以下语法:

    @Value("#{jetProperties['jetBean.name']}")
    
    <!-- define the properties file to use -->
    <util:properties id="jetProperties" location="classpath:/jet.properties" />
    

    来自http://chrislovecnm.com/2010/03/08/spring-3-java-based-configuration-with-value/

    【讨论】:

    • 感谢您的回复,但我之前尝试过,但它不起作用。我再次更改了语法及其 null...
    【解决方案3】:

    您是否在 dispatcher-servlet.xml 中添加了上下文占位符?按照这里,Spring @Value annotation in @Controller class not evaluating to value inside properties file 他们似乎已经通过添加它而不是应用程序上下文来解决它

    【讨论】:

    • 我没有 dispatcher-servlet.xml 文件,你的意思是它是 web.xml 吗?如何在此处添加
    • dispatcher-servlet.xml 是 applicationContext.xml (stackoverflow.com/questions/4549034/…) 的子上下文 dispatcher-servlet.xml(通常命名为“dispatchername”-servlet)是常见的地方存储了控制器和解析器配置(如 viewResolver)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 2018-02-12
    相关资源
    最近更新 更多