=classpath:
=d:/logs
##tomcat set###
=80
#session 超时时间
-timeout=60
###########
hello=hello china!!!
=china school
=second grade three class
[0].name=tom
[1].name=jack
在代码中@Value注入到属性中
@Controller
@RequestMapping("/")
public class HelloController {
public static Logger LOG = ();
@Value("${hello}")
private String hello;
@Value("${}")
private String schoolName;
@ConfigurationProperties
如果想把某种相关的配置,注入到某个配置类中,比如上面的中看到的配置项,想注入到ClassConfig配置类中package ;
import ;
import ;
import ;
import ;
@Component("classConfig")
@ConfigurationProperties(prefix="class")
public class ClassConfig {
private String schoolName;
private String className;
private List<StudentConfig> students = new ArrayList<StudentConfig>();
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
= schoolName;
}
public void setClassName(String className) {
= className;
}
public void setStudents(List<StudentConfig> students) {
= students;
}
public String getClassName() {
return className;
}
public List<StudentConfig> getStudents() {
return students;
}
}
这样就会把中以class.开头的配置项给注入进来
我们看到代码中@ConfigurationProperties并没有指明properties,那默认的就是。那是否有地方指明properties的路径呢?在版本1.5.1之前可以@ConfigurationProperties(prefix="class",location="classpath:/"),但是1.5.2版本没有location了,需要用@PropertySource("classpath:/")
package ;
import ;
import ;
import ;
@Component("studentConfig")
@ConfigurationProperties
@PropertySource("classpath:/")
public class StudentConfig {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
= name;
}
}
测试下
package ;
import org.;
import org.;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@Controller
@RequestMapping("/")
public class HelloController {
public static Logger LOG = ();
@Value("${hello}")
private String hello;
@Value("${}")
private String schoolName;
@Autowired
private ClassConfig classConfig;
@Autowired
private StudentConfig studentConfig;
@RequestMapping(value="/hello")
@ResponseBody
public String hello(){
("=======使用@Value注入获取.....===========");
("hello="+hello+" schoolName=" + schoolName);
("======使用@ConfigurationProperties注入获取.....============");
("schoolName=" + ());
("className=" + ());
("student[0].name=" + ().get(0).getName());
("studentConfig...name=" + ());
return "hello";
}
}
打印结果
2017-05-17 15:20:49.677 INFO 72996 --- [p-nio-80-exec-1] : FrameworkServlet 'dispatcherServlet': initialization completed in 19 ms
2017-05-17 15:20:49.677 [http-nio-80-exec-1] INFO - FrameworkServlet 'dispatcherServlet': initialization completed in 19 ms
=======使用@Value注入获取.....===========
hello=hello china!!! schoolName=china school
======使用@ConfigurationProperties注入获取.....============
schoolName=china school
className=second grade three class
student[0].name=tom
studentConfig...name=xiao hong
源码下载