无法从spring mvc中的属性文件中读取

时间:2015-12-10 11:19:21

标签: java spring spring-mvc

从.properties文件读取属性时,我总是得到null值,我使用的是spring framework 4.0.5 Release,并使用Spring STS IDE, 我的代码是这样的:

@Component
public class MenuClient {

     @Value("${menu.list}")
     private String url;

     public void showUrl() {
         System.out.println("url : " + url); //shows null
     }

}

我的弹簧配置

 <?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/mvc    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/beans http:/   /www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context.xsd">

<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

<!-- Enables the Spring MVC @Controller programming model -->


<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/assets/**" location="/resources/assets/" />
<annotation-driven />

<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

<context:component-scan base-package="com.mycompany" />

<context:property-placeholder location="classpath:config.properties" />

</beans:beans>

这是我的config.properties位置:

file location

我的项目中是否有任何丢失或错误的配置?

2 个答案:

答案 0 :(得分:1)

尝试使用它:

  <context:property-placeholder location="classpath*:config.properties" />

如果没有尝试将config.properties文件放在META-INF文件夹中并使用此文件:

   <context:property-placeholder
    location="classpath*:META-INF/config.properties" />

答案 1 :(得分:0)

我发现了问题,因为我正在创建该类的新实例。 (初学者错误)在我使用@autowired实例化我的类后,该值不为null。 感谢@ M.Deinum指出根本原因。