I just changed my new job in October, which also indicates the full shift to Java technology stack. I entered the new company with ignorant knowledge of Spring, Spring Boot, Mybatis, Maven and so on. The next day, the leader sent me a link of git warehouse and told me about our project template. In line with the principle of making the code run first, I went to various search foundation of springboot project, fortunately the template is relatively basic, can run quickly, write a Controller, connect to the local database can also run an API, I thought it is very simple, see how to run it, so I began to study the code, I instantly silly, Now it’s a YAML file, now it’s a Properties file, now it’s an XML configuration file, what does it all do, how do you use it, can you not write so many configuration files, or can you use one configuration file in one format? After two days of research and experiments, I finally roughly understand the use of various documents. These learning results are now recorded for subsequent reference. Today is the first in a series of introductory notes: Two configuration files for Spring Boot.

Although Spring Boot uses a lot of automatic configuration, it is often necessary to use configuration files in actual projects. There are two configuration file formats available in Spring Boot: —- Properties file and YAML file. The default configuration file name is application.properties(or application.yaml)

Where to put these configuration files

Since these configuration files are provided by Spring Boot by default, can I just put them in a folder? Spring Boot will look for configuration files in the following path when starting up

  • Config folder in the project root directory
  • Project root
  • The config folder in classpath
  • Under the classpath

In addition, the priorities of the four directories decrease from top to bottom. That is, if you define configuration files in the four directories, the configuration with the higher priority will be overwritten by the configuration with the lower priority. The details are shown in the figure below:

Application. The use of the properties

spring.datasource.name=datasource spring.datasource.druid.filters=stat spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.driver-class-name=com.mysql.jdbc.Driver Spring. The datasource. Url = JDBC: mysql: / / 127.0.0.1:3306 / springBucks? UseSSL = false&useUnicode = true&characterEncoding = utf-8 spring.datasource.username=yourusername spring.datasource.password=yourpasswordCopy the code

The use of the application. The yaml

spring:
  datasource:
    name: datasource
    type: com.alibaba.druid.pool.DruidDataSource
    url: JDBC: mysql: / / 127.0.0.1:3306 / test? useSSL=false&useUnicode=true&characterEncoding=UTF-8
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: dreamfinal21
    druid:
      filters: stat
      initial-size: 5
      min-idle: 5
      max-active: 20
      max-wait: 60000
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000

Copy the code

Can I change the name of the configuration file

Usually the default configuration file is sufficient, but sometimes we want to change the name of the configuration file, or change the location of the configuration file (personally not necessary), which is acceptable. The following ways can be ah;

Specify the name and location of the configuration file at startup

If you customize the default configuration file as app.properties and place it under your custom classpath:/customConfig/, specify the name and location of the configuration file at startup when you jar your project.

Java -jar properties-0.0.1 -snapshot.jar --spring.config.location=classpath:/customConfig/ --spring.config.name=appCopy the code

Of course, during the development process you can also use the IDE to specify the boot configuration, I will not elaborate here, personally do not like this way, interested in their own Internet search.

Annotate with @propertysource

The application. Properties file is the default configuration loaded when Spring Boot is started. It is not recommended to write custom configuration files, but custom configuration files are not loaded by Spring Boot by default, so use @propertysource annotations. Note also that the @peopertysource annotation does not support yamL configuration.

Here is an example of using a custom configuration. Here we have a custom configuration file user.properties that looks like this:

  user.name=zhangsan
  user.age=23
  user.id=1
Copy the code
   @Component
   @PropertySource("classpath:user.properties")
   public class User{
      @Value("${user.id}")
      private Long id;
      @Value("${user.name}")
      private String name;
      @Value("${user.age}")
      private Long age;
      //getter/setter
   }

Copy the code

Inspired by introducing custom configuration files via @propertysource, can I also load system configuration files via this annotation? I renamed the application.properties file to app.properties, moved it to classpath: /config1/, and annotated the SpringBoot boot class with the following:

  @SpringBootApplication
  @PropertySource("classpath:config1/app.properties")
  public class SpringBucksApplication {

	public static void main(String[] args) { SpringApplication.run(SpringBucksApplication.class, args); }}Copy the code

Ha-ha, it works too

Properties application-dev.properties application-prod.properties

In real projects, we usually need different configurations in different environments. For example, in development environment, test environment and online environment, the database configuration may be different. You can see application-dev.properties or application-prod.properties to help you To solve the configuration problems of different environments. The name rule for the environment configuration file that differs from the Spring Boot convention is application-{profile}.properties. {profile} is a placeholder for the name of the environment you defined. You can define different environment profiles to use, so how do I determine which profile I use? I need to specify which profile to activate in the Spring Boot configuration file, as shown below (you can also use yamL files):

// If active is defined, use the profile specified by active; otherwise, use the profile specified by default. Active =dev spring.profile.defaut=devCopy the code

Also mentioned here is the @profile annotation, which specifies that the Bean should only be assembled when a Profile is active. For example, when we want to use a different datasource in a different context, the @profile annotation comes into play. In the following example, we want to use an embedded database in our development environment, but in our online environment using the MySQL database, we can define configuration like this.


    @Bean(name="dataSource")
    @Profile("dev")
    public DataSource embeddedDataSource(a) {
      return new EmbeddedDatabaseBuilder()
              .setType(EmbeddedDatabaseType.H2)
              .addScript("classpath:schema.sql")
              .addScript("classpath:test-data.sql")
              .build();
    }

    @Bean(name="dataSource")
    @Profile("prod")
    public DataSource hikariDataSource(a) {

        HikariConfig hikariConfig = new HikariConfig();

        hikariConfig.setDriverClassName("com.mysql.jdbc.Driver");
        hikariConfig.setJdbcUrl(hikaricpUrl);
        hikariConfig.setUsername(hikaricpUsername);
        hikariConfig.setPassword(hikaricpPassword);
        hikariConfig.setAutoCommit(true);
        hikariConfig.setTransactionIsolation("TRANSACTION_READ_COMMITTED");
        hikariConfig.setConnectionTimeout(5000);
        hikariConfig.setIdleTimeout(600000);
        hikariConfig.setMaxLifetime(1800000);
        hikariConfig.setMaximumPoolSize(5);
        hikariConfig.addDataSourceProperty("cachePrepStmts"."true");
        hikariConfig.addDataSourceProperty("prepStmtCacheSize"."250");
        hikariConfig.addDataSourceProperty("prepStmtCacheSqlLimit"."2048");
        hikariConfig.addDataSourceProperty("allowMultiQueries"."true");

        HikariDataSource dataSource = new HikariDataSource(hikariConfig);

        return dataSource;
    }
Copy the code