配置属性值
application.properties
1 2 3
| server.port=8080
com.study.name=WuZhiYong
|
Environment对象读取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @RestController public class HelloController {
@Autowired private Environment env;
@GetMapping("/port") public String getPort(){ return env.getProperty("server.port"); }
}
|
运行项目 访问 http://localhost:8080/port
返回8080
@value注解读取
1 2 3 4 5 6 7
| @Value("${server.port}") private String port;
@GetMapping("/getPortByValeAnnotation") public String getPortByValeAnnotation(){ return port; }
|
prefix前缀读取
新建配置类:
1 2 3 4 5 6 7 8 9 10 11 12 13
| @ConfigurationProperties(prefix = "com.study") @Component public class MyConfig { private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; } }
|
控制器获取
1 2 3 4 5 6 7
| @Autowired private MyConfig myConfig;
@GetMapping("getPropByPrefix") public String getPropByPrefix(){ return myConfig.getName(); }
|