Exemple Spring @PropertySource
Dans Spring, vous pouvez utiliser l'annotation@PropertySource
pour externaliser votre configuration dans un fichier de propriétés. Dans ce tutoriel, nous allons vous montrer comment utiliser@PropertySource
pour lire un fichier de propriétés et afficher les valeurs avec@Value
etEnvironment
.
P.S @PropertySource has been available since Spring 3.1
1. @PropertySource et @Value
Un exemple classique, lire un fichier de propriétés et afficher avec${}
.
config.properties
mongodb.url=1.2.3.4 mongodb.db=hello
AppConfigMongoDB
package com.example.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; //... @Configuration @ComponentScan(basePackages = { "com.example.*" }) @PropertySource("classpath:config.properties") public class AppConfigMongoDB { //1.2.3.4 @Value("${mongodb.url}") private String mongodbUrl; //hello @Value("${mongodb.db}") private String defaultDb; @Bean public MongoTemplate mongoTemplate() throws Exception { MongoClientOptions mongoOptions = new MongoClientOptions.Builder().maxWaitTime(1000 * 60 * 5).build(); MongoClient mongo = new MongoClient(mongodbUrl, mongoOptions); MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongo, defaultDb); return new MongoTemplate(mongoDbFactory); } //To resolve ${} in @Value @Bean public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() { return new PropertySourcesPlaceholderConfigurer(); } }
Note
Pour résoudre $ \ {} en@Values
, vous devez enregistrer unPropertySourcesPlaceholderConfigurer
statique dans un fichier de configuration XML ou d'annotation.
2. @PropertySource et environnement
Spring recommande d'utiliserEnvironment
pour obtenir les valeurs de propriété.
AppConfigMongoDB
package com.example.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; //... @Configuration @ComponentScan(basePackages = { "com.example.*" }) @PropertySource("classpath:config.properties") public class AppConfigMongoDB { @Autowired private Environment env; @Bean public MongoTemplate mongoTemplate() throws Exception { String mongodbUrl = env.getProperty("mongodb.url"); String defaultDb = env.getProperty("mongodb.db"); MongoClientOptions mongoOptions = new MongoClientOptions.Builder().maxWaitTime(1000 * 60 * 5).build(); MongoClient mongo = new MongoClient(mongodbUrl, mongoOptions); MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongo, defaultDb); return new MongoTemplate(mongoDbFactory); } }
3. Plus d'exemples @PropertySource
Exemples plus courants.
3.1 Example to resolve $\{} within @PropertySource
resource locations.
@Configuration @PropertySource("file:${app.home}/app.properties") public class AppConfig { @Autowired Environment env; }
Définissez une propriété système au démarrage.
System.setProperty("app.home", "test"); java -jar -Dapp.home="/home/mkyon/test" example.jar
3.2 Include multiple properties files.
@Configuration @PropertySource({ "classpath:config.properties", "classpath:db.properties" //if same key, this will 'win' }) public class AppConfig { @Autowired Environment env; }
Remarque
Si une clé de propriété est dupliquée, le dernier fichier déclaré sera «gagnant» et écrasé.
4. Spring 4 et @PropertySources
Quelques améliorations sur Spring 4.
4.1 Introduces new @PropertySources
to support Java 8 and better way to include multiple properties files.
@Configuration @PropertySources({ @PropertySource("classpath:config.properties"), @PropertySource("classpath:db.properties") }) public class AppConfig { //... }
4.2 Allow @PropertySource
to ignore the not found properties file.
@Configuration @PropertySource("classpath:missing.properties") public class AppConfig { //... }
Simissing.properties
n'est pas trouvé, le système ne peut pas démarrer et lanceFileNotFoundException
Caused by: java.io.FileNotFoundException: class path resource [missiong.properties] cannot be opened because it does not exist
Au printemps 4, vous pouvez utiliserignoreResourceNotFound
pour ignorer le fichier de propriétés non trouvé
@Configuration @PropertySource(value="classpath:missing.properties", ignoreResourceNotFound=true) public class AppConfig { //... }
@PropertySources({ @PropertySource(value = "classpath:missing.properties", ignoreResourceNotFound=true), @PropertySource("classpath:config.properties") })
Terminé.