The above shows that we all write the configuration file to Application.yml. Sometimes we do not want to write the configuration to the application configuration file, we need to customize the configuration file, such as test.properties:
Com.forezp.name=forezpcom.forezp.age=12
How do you assign this profile information to a JavaBean?
@Configuration @propertysource (value = "Classpath:test.properties") @ConfigurationProperties (prefix = "Com.forezp") public class User { private String name; private int age; Public String GetName () { return name; } public void SetName (String name) { this.name = name; } public int getage () { return age; } public void Setage (int.) { this.age = age; }}
In the latest version of Springboot, you need to add these three annotations.
@Configuration @PropertySource (value = "Classpath:test.properties") @ConfigurationProperties (prefix = "Com.forezp"); The 1.4 version requires Propertysource plus location. @RestController @enableconfigurationproperties ({configbean.class,user.class}) public class Lucycontroller { @ autowired Configbean Configbean; @RequestMapping (value = "/lucy") public String Miya () { return configbean.getgreeting () + ">>>>" + Configbean.getname () + ">>>>" + configbean.getuuid () + ">>>>" +configbean.getmax (); @Autowired user user; @RequestMapping (value = "/user") public String User () { return user.getname () +user.getage ();} }
Start the project, open localhost:8080/user; The browser will display:
forezp12
Four, multiple environment configuration files
In a real-world development environment, we need a different configuration environment, in the format application-{profile}.properties, where {profile} corresponds to your environment identity, such as:
- Application-test.properties: Test environment
- Application-dev.properties: Development environment
- Application-prod.properties: Production environment
How to use? We only need to add in the APPLICATION.YML:
Spring: Profiles: Active:dev
Among them application-dev.yml:
Server: port:8082
Start the project and discover that the port of the program is no longer 8080, but 8082.
Source Source
Enterprise Distribution Micro Service Cloud Springcloud springboot MyBatis (19) Spring Boot Custom configuration file