Any class that is managed by spring implements the interface Environmentaware override method Setenvironment to get the variables in the system environment variables and application configuration files when Project starts.
Such as:
@Configuration Public class mywebappconfigurer implements environmentaware { Private Static FinalLogger Logger = Loggerfactory.getlogger (Mywebappconfigurer.class);PrivateRelaxedpropertyresolver Propertyresolver;@Value("${spring.datasource.url}")PrivateString Myurl;/** * This method does not test the implementation of the Environmentaware interface, the method of reading environment variables. */ @Override Public void setenvironment(Environment env) {Logger.info (Env.getproperty ("Java_home")); Logger.info (Myurl); String str = Env.getproperty ("Spring.datasource.url"); Logger.info (str); Propertyresolver =NewRelaxedpropertyresolver (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 run when the system is started.
Or, for example, the following controller:
@Controllerpublicclass PageController implements EnvironmentAware{ @Override publicvoidsetEnvironment(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. The condition here is that Mongo.class is located on the classpath
- @EnableConfigurationProperties will spring The Spring.data.mongodb.* property in the Boot configuration file (application.properties) is mapped to mongoproperties and injected into 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 bean of its own definition takes precedence over the default configuration of the framework, and we assume that a MONGO object is explicitly defined in the business code, so spring boot is no longer created.
"spring.data.mongodb")publicclass MongoProperties { private String host; privateint port = DBPort.PORT; private"mongodb://localhost/test"; private String database; // ... getters/ setters omitted
It is a property prefixed with SPRING.DATA.MONGODB and then mapped directly to the properties of the object by name, and some default values are included at the same time. Assuming not configured, then Mongo.uri is mongodb://localhost/test.
Spring Boot environment variable reading and binding of Property objects