一、在高版本的springboot中,@ConfigurationProperties(prefix = "wisely2",locations = "classpath:wisely.properties")这个注解不支持了,所以我们要另辟蹊径
二、使用组合式注解:
1、自定义config.properties文件:
1 config.fileServer=/root/jzyp/staticserver/webapps/ROOT/server 2 config.staticServer=http://101.201.77.138:8080/server
2、建立Testconfig类:
1 package main.config; 2 3 import org.springframework.boot.context.properties.ConfigurationProperties; 4 import org.springframework.context.annotation.Configuration; 5 import org.springframework.context.annotation.PropertySource; 6 7 @Configuration //保证该类会被扫描到 8 @ConfigurationProperties(prefix = "config") //读取前缀为 config 的内容 9 @PropertySource("classpath:config.properties") //定义了要读取的properties文件的位置 10 public class TestConfig { 11 public String fileServer; 12 public String staticServer; 13 14 public String getFileServer() { 15 return fileServer; 16 } 17 18 public void setFileServer(String fileServer) { 19 this.fileServer = fileServer; 20 } 21 22 public String getStaticServer() { 23 return staticServer; 24 } 25 26 public void setStaticServer(String staticServer) { 27 this.staticServer = staticServer; 28 } 29 30 }
3、建立测试类controller:
1 @RestController 2 public class RCacheDemoController { 3 4 @Autowired 5 TestConfig testConfig; 6 @Autowired 7 Test2Config test2Config; 8 9 @GetMapping("/testConfig") 10 public String testConfig(){ 11 System.out.println("fileServer:"+testConfig.getFileServer()+"/asdasd"); 12 System.out.println("staticServer:"+testConfig.getStaticServer()+"/dasd");13 return "testConfig"; 14 15 }
4、使用@ConfigurationProperties 注解 要在启动处加上@EnableConfigurationProperties(TestConfig.class):
1 @SpringBootApplication 2 @EnableConfigurationProperties(TestConfig.class) 3 public class Applicaiton { 4 5 6 public static void main(String[] args) { 7 SpringApplication.run(Applicaiton.class, args); 8 } 9 }
二、第二种就是使用@Value这个注解了,不多解释:
1 package main.config; 2 3 import org.springframework.beans.factory.annotation.Value; 4 import org.springframework.context.annotation.Configuration; 5 import org.springframework.context.annotation.PropertySource; 6 7 @Configuration 8 @PropertySource("classpath:config.properties") 9 public class Test2Config { 10 @Value("${config.fileServer}") 11 public String fileServer; 12 @Value("${config.staticServer}") 13 public String staticServer; 14 15 public String getFileServer() { 16 return fileServer; 17 } 18 19 public void setFileServer(String fileServer) { 20 this.fileServer = fileServer; 21 } 22 23 public String getStaticServer() { 24 return staticServer; 25 } 26 27 public void setStaticServer(String staticServer) { 28 this.staticServer = staticServer; 29 } 30 31 }
ps:和上面一样的测试方法,两种方法读取。