spring boot 获取spring配置信息的方式

spring boot应用程序获取配置文件的配置信息的方法:

1.通过@Value注释获取

2.通过Environment类获取

3.通过@ConfigurationProperties获取

application.properties文件内容:

1 server.port=8080
2 
3 
4 spring.main.banner-mode=off
5 
6 myconfig.mail.port=1234
View Code

myconfig.properties文件内容:

1 myconfig.mail.address=localhost
2 myconfig.mail.userName=myuser
View Code

HelloController.java文件内容:

 1 import javax.annotation.Resource;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.beans.factory.annotation.Value;
 5 import org.springframework.boot.context.properties.ConfigurationProperties;
 6 import org.springframework.context.annotation.Configuration;
 7 import org.springframework.context.annotation.PropertySource;
 8 import org.springframework.core.env.Environment;
 9 import org.springframework.stereotype.Component;
10 import org.springframework.web.bind.annotation.RequestMapping;
11 import org.springframework.web.bind.annotation.RestController;
12 
13 @RestController
14 public class HelloController {
15     @Resource
16     private Environment environment;
17     
18     @Value("${server.port}")
19     private String port;
20     
21     @Autowired
22     MyconfigProperties myconfig;
23     
24     @RequestMapping("/hello")
25     public String Hello() {
26         System.out.println("server.port=" + environment.getProperty("server.port"));
27         System.out.println("server.port=" + port);
28         
29         System.out.println("address=" + myconfig.getAddress() + ",userName=" + myconfig.getUserName() + ",port=" + myconfig.getPort());
30         
31         return "Hello world!";
32     }
33 }
34 
35 @Component
36 @PropertySource({"classpath:myconfig.properties","classpath:application.properties"})
37 @ConfigurationProperties(prefix= "myconfig.mail")
38 class MyconfigProperties {
39     private String address;
40     private String userName;
41     private Integer port;
42     
43     public Integer getPort() {
44         return port;
45     }
46     public void setPort(Integer port) {
47         this.port = port;
48     }
49     public String getAddress() {
50         return address;
51     }
52     public void setAddress(String address) {
53         this.address = address;
54     }
55     
56     public String getUserName() {
57         return userName;
58     }
59     public void setUserName(String userName) {
60         this.userName = userName;
61     }
62 }
View Code

猜你喜欢

转载自www.cnblogs.com/labing/p/12729537.html