昨天看到项目里一个Config类,加载一个properties文件,通过IO流去读取并加载到Property类里,感觉太过复杂,印象中有Spring @Value标签可以使用,就研究了一下。
目的:使用@Value来注入配置在properties文件中的key-value,使用@Value必须是托管在spring ioc容器中的bean
方法:你可以直接使用@Value注入全局变量,也可以注入setter方法
碰到的问题:我在注入controller类的时候,注入失败,注入其它类可以,原因是没有在web.xml->Spring的DispatcherServlet->contextConfigLocation指定的xml中配置PropertySourcesPlaceholderConfigurer
相关代码:
xml:
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:spring_*.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
也可以使用@Configurable @PropertySource,来使用一个配置类替换XML
package com.smith.config;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.stereotype.Component;
@Configurable
@PropertySource("classpath:spring_test.properties")
public class SmithConfig {
}
Properties:在Maven项目下resource下建一个spring_开头的properties文件
Controller类:
package com.smith.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.smith.config.SmithConfig;
@Controller
@RequestMapping("/helloSmith")
@Import(SmithConfig.class)
public class PropertyController {
@Value("${abc}")
private String abc;
/*
@Autowired
private SmithConfig config;*/
@RequestMapping(value="/showProperty", method = { RequestMethod.POST, RequestMethod.GET })
public void showCardNoPage() {
System.out.println(abc);
}
}