Beispiel für Spring @PropertySource

In Spring können Sie die Annotation@PropertySourceverwenden, um Ihre Konfiguration in eine Eigenschaftendatei zu externalisieren. In diesem Tutorial zeigen wir Ihnen, wie Sie mit@PropertySource eine Eigenschaftendatei lesen und die Werte mit@Value undEnvironment anzeigen.
P.S @PropertySource has been available since Spring 3.1
1. @PropertySource und @Value
Ein klassisches Beispiel: Lesen Sie eine Eigenschaftendatei und zeigen Sie sie mit${} an.
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
Um $ \ {} in@Values aufzulösen, müssen Sie statischePropertySourcesPlaceholderConfigurer entweder in einer XML- oder einer Anmerkungskonfigurationsdatei registrieren.
2. @PropertySource und Umgebung
Spring empfiehlt,Environment zu verwenden, um die Eigenschaftswerte abzurufen.
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. Weitere @ PropertySource-Beispiele
Häufigere Beispiele.
3.1 Example to resolve $\{} within @PropertySource resource locations.
@Configuration
@PropertySource("file:${app.home}/app.properties")
public class AppConfig {
@Autowired
Environment env;
}
Legen Sie beim Start eine Systemeigenschaft fest.
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;
}
Hinweis
Wenn ein Eigenschaftsschlüssel dupliziert wird, wird die zuletzt deklarierte Datei "gewinnen" und überschreiben.
4. Spring 4 und @PropertySources
Einige Verbesserungen an 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 {
//...
}
Wennmissing.properties nicht gefunden wird, kann das System nicht starten und wirftFileNotFoundException
Caused by: java.io.FileNotFoundException:
class path resource [missiong.properties] cannot be opened because it does not exist
In Spring 4 können SieignoreResourceNotFound verwenden, um die nicht gefundene Eigenschaftendatei zu ignorieren
@Configuration
@PropertySource(value="classpath:missing.properties", ignoreResourceNotFound=true)
public class AppConfig {
//...
}
@PropertySources({
@PropertySource(value = "classpath:missing.properties", ignoreResourceNotFound=true),
@PropertySource("classpath:config.properties")
})
Erledigt.