通过@Value将外部配置文件的值动态注入到Bean中。配置文件主要有两类:
application.properties/application.yml。这两个配置文件在spring boot启动时默认加载此文件
自定义属性文件。自定义属性文件通过@PropertySource加载。@PropertySource可以同时加载多个文件,也可以加载单个文件。如果相同第一个属性文件和第二属性文件存在相同key,则最后一个属性文件里的key启作用。
源码
//用于方法、参数、注解
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {
String value();
}
示例
第一种默认配置文件
在application.properties文件中配置好
user.address=Beijing
java代码中
@Controller
@RequestMapping("/user")
public class ControllerDemo {
@Value("${user.address}")
private String userAddress;
@Resource
private UserServiceImpl userService;
@RequestMapping(value = "/index")
@ResponseBody
public String index() {
//下面打印出:Beijing
System.out.println(userAddress);
userService.test();
return "ok";
}
}
另外application.yml 获取方式一样,只是两种配置文件的样式不同。注意:yml文件中的冒号后面要有空格,冒号+空格=properties文件中的点.。
第二种自定义配置文件
新建Myconfig.properties,放置于resources目录下,配置项如下:
net.address=www.baidu.com
net.address=www.sina.com
java代码
@Component
@PropertySource({"classpath:/Myconfig.properties"})
public class ConfigurationFileInject {
@Value("${net.address}")
private String userLog;
public String getUserLog() {
return this.userLog;
}
}
@Controller
@RequestMapping("/user")
public class ControllerDemo {
@Resource
private ConfigurationFileInject configurationFileInject;
@RequestMapping(value = "/index")
@ResponseBody
public String index() {
String userBlog=configurationFileInject.getUserLog();
//下面打印出:www.sina.com
System.out.println(userBlog);
return "ok";
}
}
通常用来获取配置文件中的配置项。