@Value在一个类中始终为null

时间:2015-08-08 09:53:19

标签: java spring spring-mvc properties

我是Spring的新手,现在我正在尝试处理@Value注释。我有两节课。一个有注释:

public class RssHandler {
    @Value("${theTopic}")
    private String theTopic;
    ...

另一个:

public class RestCallImpl implements RestCall {
    @Value("${senderUrl}")
    private String senderUrl;
    ...

我的属性文件是:

theTopic=mytopic
senderUrl=http://localhost:8080/

我的bean xml包含了我在这里找到的所有东西,例如propertyConfigurer和beans声明(据我所知):

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:int="http://www.springframework.org/schema/integration"
       xmlns:feed="http://www.springframework.org/schema/integration/feed"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/integration
                           http://www.springframework.org/schema/integration/spring-integration.xsd
                           http://www.springframework.org/schema/integration/feed
                           http://www.springframework.org/schema/integration/feed/spring-integration-feed.xsd">

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="locations">
          <list>
            <value>classpath:application.properties</value>
            <value>file:/Users/Projects/Java/TestNotifier/resources/application.properties</value>
          </list>
      </property>
      <property name="ignoreUnresolvablePlaceholders" value="true"/>
      <property name="ignoreResourceNotFound" value="true"/>
    </bean>

    <!-- RSS Stuff -->
    <int:channel id="inputRssFeedChannel"/>

    <feed:inbound-channel-adapter id="news"
                                  channel="inputRssFeedChannel"
                                  url="http://feeds.feedburner.com/Techcrunch">
        <int:poller fixed-rate=5000 max-messages-per-poll=100/>
    </feed:inbound-channel-adapter>

    <int:service-activator input-channel="inputRssFeedChannel"
                           ref="rssPrintOutService"
                           method="printRss"/>

    <bean id="rssPrintOutService" class="TestNotifier.RssHandler"/>
    <bean id="SnsRestCall" class="TestNotifier.RestCallImpl"/>
</beans>

当我运行我的应用程序时,我完全得到“theTopic”,但“senderUrl”总是空的。为什么这样?我错过了什么?提前谢谢!

2 个答案:

答案 0 :(得分:0)

您可以尝试@PropertySource注释到您的班级,如下所示

@Configuration
@PropertySource(value="classpath:application.properties")
public class RestCallImpl implements RestCall {

    @Value("${senderUrl}")
    private String senderUrl;

}

答案 1 :(得分:0)

尝试使用以下内容:

public class RestCallImpl implements RestCall {

  @Value("#{senderUrl}")
    private String senderUrl;
    ...

基本上只需将'$'更改为'#'。