Any class that is managed by spring implements the interface Environmentaware override method Setenvironment can get the variables in the system environment variables and application configuration files when the project starts.
Such as:
@ConfigurationPublicClassMywebappconfigurerImplementsEnvironmentaware {PrivateStaticFinal Logger Logger = Loggerfactory.getlogger (Mywebappconfigurer.class);private relaxedpropertyresolver propertyresolver; @Value ( "${spring.datasource.url}") private String Myurl; /** * This method is only to test the implementation of the Environmentaware interface, read the environment variable method. */ @Override public void setenvironment (Environment env) {Logger.info (Env.getproperty ( "Spring.datasource.url"); Logger.info (str); propertyresolver = new relaxedpropertyresolver (env, "Spring.datasource."); String url = propertyresolver.getproperty ( "url"); Logger.info (URL);}}
@Controller @Service are supported by spring-managed classes, and note that the overridden method setenvironment is executed when the system is started.
or controller as follows:
@Controllerpublic class PageController implements EnvironmentAware{ @Override public void setEnvironment(Environment environment) { String s = environment.getProperty("JAVA_HOME"); System.out.println(s); }}
We can also read the properties in the Application property configuration file via @configurationproperties.
@Configuration @ConditionalOnClass (mongo.class) @ Enableconfigurationproperties (mongoproperties.class) public class mongoautoconfiguration { @Autowired private mongoproperties properties;}
The
- @ConditionOnClass indicates that the @configuration is loaded only under certain conditions, where Mongo.class is located on the classpath
- @ Enableconfigurationproperties the spring.data.mongodb.* in the Spring boot configuration file (application.properties) The attribute is mapped to mongoproperties and injected into the mongoautoconfiguration. The
- @ConditionalOnMissingBean indicates that spring boot instantiates a bean only if the MONGO object does not exist in the current context. This logic also embodies another feature of spring boot-the custom bean takes precedence over the default configuration of the framework, and if we explicitly define a MONGO object in the business code, Spring boot is no longer created.
"spring.data.mongodb")public class MongoProperties { private String host; private int port = DBPort.PORT; private String uri = "mongodb://localhost/test"; private String database; // ... getters/ setters omitted}
It is a property prefixed with Spring.data.MongoDB, and then directly mapped to the object's properties by name, along with some default values. If not configured, then Mongo.uri is mongodb://localhost/test.
XV, Spring Boot environment variable reads and binding of Property objects