This section describes several common attribute configuration methods. There are 17 official methods. For other methods, please check the official documents.

1. Start the class to add attributes

Properties = new Properties(); Properties.setproperty (" SLOGAN "," I love you, dear girl "); springApplication.setDefaultProperties(properties);Copy the code

Get attributes from Environment

@Component @Order(4) public class ResultCommandLineRunner implements CommandLineRunner, EnvironmentAware { private Environment environment; @Override public void run(String... args) throws Exception { String slogan = environment.getProperty("slogan"); System.out.println(slogan); } @Override public void setEnvironment(Environment environment) { this.environment = environment; }}Copy the code

Console print results

2. Configure the properties file or YML file

Application – default. Yml is the default

Note that yML takes precedence over properties. Create a demo.properties file in the Resources directory with the following contents:

poster=hello world
Copy the code

The launch class adds the @propertysource ({“demo.properties”}) annotation

Get attributes from Environment

@Component @Order(4) public class ResultCommandLineRunner implements CommandLineRunner, EnvironmentAware { private Environment environment; @Override public void run(String... args) throws Exception { String slogan = environment.getProperty("slogan"); System.out.println(slogan); String poster = environment.getProperty("poster"); System.out.println(poster); } @Override public void setEnvironment(Environment environment) { this.environment = environment; }}Copy the code

Console print results

Set the file priority

Properties > application-default.yml > Application.properties > application.yml