在SpringMVC+Spring+Mybatis项目中使用@Value的时候,在Controller无法获取@Value对应的值。
1.属性文件 sys.properties
MAIL_HOST_KEY=mail.smtp.host MAIL_HOST_VALUE=smtp.163.com
2.我是在applicationContext.xml引入sys.properties
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> <value>classpath:sys.properties</value> <!-- <value>file:/opt/demo/config/demo-remote.properties</value> --> </list> </property> </bean>3.在Controller中的使用
@RequestMapping(value = "/server") @Controller @Slf4j public class DispatcherController { // 发送方邮件服务器地址 @Value("${MAIL_HOST_KEY}") private String MAIL_HOST_KEY; @Value("${MAIL_HOST_VALUE}") private String MAIL_HOST_VALUE; }
4.没有获取到值的原因是applicationContext加载的是父容器,父容器在项目启动的时候就被加载了。SpringMVC对应的配置文件加载的是子容器,子容器可以访问父容器的对象,但是不能访问加载的配置文件。如果想在SpringMVC中使用加载的配置文件,需要在SpringMVC对应的配置文件中引入该属性文件。
在spring-mvc.xml中加入如下即可
<context:property-placeholder location="classpath:sys.properties" />