@ProtertySource
@PropertySouce is based on java config notes were introduced in spring3.1.
By @PropertySource annotations stored value profile properties to the Spring of the Environment, Interface Environment provides a method to read the value in the configuration file, the key value of the parameter is defined in the properties file.
@Configuration
@ProtertySource("classpath:/com/soundsystem/app.properties")
public class ExpressiveConfig{
@Autowired
Environment ent;
@Bean
public BlankDisc disc(){
return new BlankDisc(
env.getPropert("disc.title"),
env.getProperty("disc.artist"));
}
}
app.properties contents of the file:
disc.title=this is title value
disc.artist= this is artist value
This property file will be loaded into the Spring of Environment. It is then obtained by getProperty () method.
Environment
public String getProperty(String key) public String getProperty(String key, String defaultValue) <T> T getProperty(String key, Class<T> targetType); <T> T getProperty(String key, Class<T> targetType, T defaultValue);
The first two forms of getProperty () method returns a value of type String, the second value if no response is received, then the default value
The third and fourth will return an object, such as Integer type we need, if get the value of type String, also need to be converted to type Integer
int count = env.getProperty ( "jdbc.connection.count", Integer.class, 30); // get the maximum number of connections to the database connection pool, default 30
Environment also provides several property-related methods.
getRequiredProperty();
If you do not specify a default value when using the getProperty, and the value of this property is not defined, then this will return null, if you want to define this property value, you can use getRequiredProperty () method, as follows
env.getRequiredProperty ( "disc.title");
Here, if the property is not defined, it will throw an IllegalStateException.
containsProperty();
If the check is present, you can call containsProperty () method
boolean titleExists = env.containsProperty("disc.title");
getPropertyAsClass()
If you want to resolve to the class of property, use getPropertyAsClass () method
Class<CompactDisc> cdClass = env.getPropertyAsClass("disc.class",CompactDisc.class);
Environment also provides several ways to check which profile is active
String [] getActiveProfiles (); Returns the value of the activation profile name
String [] getDefaultProfiles (); return to default value profile name
boolean acceptsProfiles (String ... Profiles); if Environment to support a given profile, then returns true