Spring Boot configuration file parsing

Spring Boot uses a global configuration file application.properties.

 

--- Custom Properties---

application.properties provides support for custom properties, so we can configure some constants here:

com.example.name=\u674E\u96F7
com.example.want=\u6765\u4E00\u676FSpring

Then, you can bind to the property you want by annotating @Value(value=”${config.name}”) directly where you want to use it

@RestController
public class UserController {
	
    @Value("${com.example.name}")
    private  String name;
	
    @Value("${com.example.want}")
    private  String want;
    
    @RequestMapping("/want")
    public String doWant(){
        return name + "," + want;
    }
    
}

Sometimes there are too many properties, and it is too tiring to bind one by one to the property fields. Officially, it is recommended to bind a bean of an object. Here we build a ConfigBean.java class, and the annotation @ConfigurationProperties (prefix = “com.example”) needs to be used at the top. to indicate which to use

@ConfigurationProperties(prefix = "com.example")
public class ConfigBean {
    private String name;
	
    private String want;

    // Omit get, set methods

}
After configuring here, you need to add @EnableConfigurationProperties to the spring Boot entry class and indicate which bean to load. If you don't write ConfigBean.class, you can add it on the bean class.
@RestController
@SpringBootApplication
@EnableConfigurationProperties({ConfigBean.class})
public class MySpringBootApplication {
	@RequestMapping("/")
	public String index(){
		return "Hello Spring Boot";
	}
	
	public static void main(String[] args) {
		SpringApplication.run(MySpringBootApplication.class, args);
	}
}
Finally, you can use ConfigBean in the Controller
@RestController
public class UserController {
    @Autowired
    private ConfigBean configBean;
    
    @RequestMapping("/want")
    public String doWant(){
        return configBean.getName() + "," + configBean.getWant();
    }
    
}
 

 

--- Reference between parameters ---

It can also be used by direct reference between the various parameters in application.properties, like the following settings:

com.example.hope=${com.example.name}\u7684\u613F\u671B${com.example.want}

 

--- Use a custom configuration file ---

Sometimes we don't want to put all the configuration in application.properties. At this time, we can customize a file: test.properties, and the path is placed under src/main/resources.

com.hx.company=\u6052\u5927
com.hx.address=\u4E0A\u6D77\u6D66\u4E1C

Create a new bean

@Configuration
@ConfigurationProperties(prefix = "com.hx")
@PropertySource("classpath:test.properties")
public class ConfigTestBean {
    private String company;
	
    private String address;

    // Omit get, set methods

}
Note that if you are using a version before 1.5, you can specify the location of the properties file through locations, like this:
@ConfigurationProperties(prefix = "config2",locations="classpath:test.properties")
 

--- Random value configuration ---

${random} in the configuration file can be used to generate various types of random values, thus simplifying the trouble of code generation, such as generating int values, long values ​​or strings.

com.example.secret=${random.value}
com.example.number=${random.int}
com.example.bignumber=${random.long}
com.example.uuid=${random.uuid}
com.example.number.less.than.ten=${random.int(10)}
com.example.number.in.range=${random.int[1024,65536]}

 

--- External configuration - command line parameter configuration ---

Spring Boot runs based on jar packages, and the programs that are packaged into jar packages can be run directly through the following commands:

java -jar xx.jar
You can modify the tomcat port number with the following command:
java -jar xx.jar --server.port=9090

It can be seen that the two consecutive minus signs in the command line are --the application.propertiesidentifiers for assigning the attribute values ​​in the command line.
So it is java -jar xx.jar --server.port=9090equivalent to application.propertiesadding a property server.port=9090in .


If you are afraid of the risk of the command line, you can disable it with SpringApplication.setAddCommandLineProperties(false) .

 

In fact, there are multiple ways to set up a Spring Boot application, and Spring Boot can obtain properties from multiple property sources, including the following:

  1. DevTools global settings properties in the root directory (when the DevTools is activated ~/.spring-boot-devtools.properties).
  2. @TestPropertySource annotation in tests.
  3. @SpringBootTest#properties annotated properties in tests.
  4. command line arguments
  5. SPRING_APPLICATION_JSONproperties in (environment variables or inline JSON embedding in system properties).
  6. ServletConfigInitialization parameters.
  7. ServletContextInitialization parameters.
  8. JNDI properties in java:comp/env
  9. JVM system properties
  10. operating system environment variables
  11. Randomly generated properties prefixed with random.* (you can apply them when setting other properties, such as ${random.long})
  12. application.properties or application.yml files outside the application
  13. 打包在应用程序内的application.properties或者appliaction.yml文件
  14. 通过@PropertySource标注的属性源
  15. 默认属性(通过SpringApplication.setDefaultProperties指定).

这里列表按组优先级排序,也就是说,任何在高优先级属性源里设置的属性都会覆盖低优先级的相同属性,列如我们上面提到的命令行属性就覆盖了application.properties的属性。

 

--- 配置文件的优先级 ---

application.properties和application.yml文件可以放在一下四个位置:

  • 外置,在相对于应用程序运行目录的/congfig子目录里。
  • 外置,在应用程序运行的目录里
  • 内置,在config包内
  • 内置,在Classpath根目录

同样,这个列表按照优先级排序,也就是说,src/main/resources/config下application.properties覆盖src/main/resources下application.properties中相同的属性。

此外,如果你在相同优先级位置同时有application.propertiesapplication.yml,那么application.yml里面的属性就会覆盖application.properties里的属性。

 

--- Profile - 多环境配置 ---

当应用程序需要部署到不同运行环境时,一些配置细节通常会有所不同。
如果按照以前的做法,就是每次发布的时候替换掉配置文件,这样太麻烦了,Spring Boot的Profile就给我们提供了解决方案,命令带上参数就搞定。

 

这里我们来模拟一下,只是简单的修改端口来测试
在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,比如:

  • application-dev.properties:开发环境
  • application-prod.properties:生产环境

想要使用对应的环境,只需要在application.properties中使用spring.profiles.active属性来设置,值对应上面提到的{profile},这里就是指dev和prod。


当然你也可以用命令行启动的时候带上参数:

java -jar xxx.jar --spring.profiles.active=dev

除了可以用profile的配置文件来分区配置我们的环境变量,在代码里,我们还可以直接用@Profile注解来进行配置,例如数据库配置,这里我们先定义一个接口

public  interface DBConnector { 
    public  void  configure(); 
}

分别定义两个实现类来实现它

/**
  * 测试数据库
  */
@Component
@Profile("testdb")
public class TestDBConnector implements DBConnector {
    @Override
    public void configure() {
        System.out.println("testdb");
    }
}
/**
 * 生产数据库
 */
@Component
@Profile("devdb")
public class DevDBConnector implements DBConnector {
    @Override
    public void configure() {
        System.out.println("devdb");
    }
}

通过在配置文件激活具体使用哪个实现类

spring.profiles.active=testdb

然后就可以这么用了

@RestController
@RequestMapping("/task")
public class TaskController {

    @Autowired 
    DBConnector connector ;

    @RequestMapping(value = {"/",""})
    public String hellTask(){

        connector.configure();    
        return "hello task !! myage is " + myage;
    }
}

除了spring.profiles.active来激活一个或者多个profile之外,还可以用spring.profiles.include来叠加profile

spring.profiles.active: testdb  
spring.profiles.include: proddb,prodmq

 

http://tengj.top/2017/02/28/springboot2/#

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326397939&siteId=291194637