Spring @PropertySource注解示例

x33g5p2x  于2022-10-06 转载在 Spring  
字(8.3k)|赞(0)|评价(0)|浏览(753)

在Spring中,你可以使用@PropertySource注解来将你的配置外化为一个属性文件。在这篇文章中,我们将讨论如何使用@PropertySource来读取属性文件,并用@ValueEnvironment来显示其值。

@PropertySource注解为添加e1d5d1到Spring的环境提供了一个方便的声明性机制。要与@Configuration类一起使用。

Spring @PropertySource注解的简单例子

在这个例子中,我们从config.properties文件中读取数据库配置,并使用Environment将这些属性值设定为DataSourceConfig class。

  1. import org.springframework.beans.factory.InitializingBean;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.context.annotation.PropertySource;
  5. import org.springframework.core.env.Environment;
  6. @Configuration
  7. @PropertySource("classpath:config.properties")
  8. public class ProperySourceDemo implements InitializingBean {
  9. @Autowired
  10. Environment env;
  11. @Override
  12. public void afterPropertiesSet() throws Exception {
  13. setDatabaseConfig();
  14. }
  15. private void setDatabaseConfig() {
  16. DataSourceConfig config = new DataSourceConfig();
  17. config.setDriver(env.getProperty("jdbc.driver"));
  18. config.setUrl(env.getProperty("jdbc.url"));
  19. config.setUsername(env.getProperty("jdbc.username"));
  20. config.setPassword(env.getProperty("jdbc.password"));
  21. System.out.println(config.toString());
  22. }
  23. }

Spring @PropertySource注解占位符示例

任何存在于@PropertySource资源位置的${...}占位符都将根据已经针对该环境注册的属性源集合进行解析。 

例如。

  1. import org.springframework.beans.factory.InitializingBean;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.context.annotation.PropertySource;
  5. import org.springframework.core.env.Environment;
  6. @Configuration
  7. @PropertySource("classpath:/com/${my.placeholder:default/path}/config.properties")
  8. public class ProperySourceDemo implements InitializingBean {
  9. @Autowired
  10. Environment env;
  11. @Override
  12. public void afterPropertiesSet() throws Exception {
  13. setDatabaseConfig();
  14. }
  15. private void setDatabaseConfig() {
  16. DataSourceConfig config = new DataSourceConfig();
  17. config.setDriver(env.getProperty("jdbc.driver"));
  18. config.setUrl(env.getProperty("jdbc.url"));
  19. config.setUsername(env.getProperty("jdbc.username"));
  20. config.setPassword(env.getProperty("jdbc.password"));
  21. System.out.println(config.toString());
  22. }
  23. }

假设 "my.placeholder "存在于一个已经注册的属性源中,例如系统属性或环境变量,该占位符将被解析为相应的值。如果没有,那么 "default/path "将被作为默认值使用。如果没有指定默认值,并且一个属性不能被解析,那么就会抛出一个IllegalArgumentExceptionwil。

@PropertySources 注解 - 包括多个属性文件

引入了新的@PropertySources,以支持Java 8和一个更好的方法来包括多个属性文件。

  1. @Configuration
  2. @PropertySources({
  3. @PropertySource("classpath:config.properties"),
  4. @PropertySource("classpath:db.properties")
  5. })
  6. public class AppConfig {
  7. //...
  8. }

允许 @PropertySource 忽略未找到的属性文件。

  1. @Configuration
  2. @PropertySource("classpath:missing.properties")
  3. public class AppConfig {
  4. //...
  5. }

如果没有找到missing.properties,系统无法启动并抛出FileNotFoundException

  1. Caused by: java.io.FileNotFoundException:
  2. classpath resource [missiong.properties] cannot be opened because it does not exist

在Spring 4中,你可以使用e1d15d1来忽略未找到的属性文件

  1. @Configuration
  2. @PropertySource(value="classpath:missing.properties", ignoreResourceNotFound=true)
  3. public class AppConfig {
  4. //...
  5. }
  6. @PropertySources({
  7. @PropertySource(value = "classpath:missing.properties", ignoreResourceNotFound=true),
  8. @PropertySource("classpath:config.properties")
  9. })

Spring @PropertySource注解完整示例

让我们创建一个简单的Spring boot maven项目来快速启动。

在这个例子中,我们从文件config.properties文件中读取数据库配置,并将这些属性值设置为DataSourceConfigclass。
使用Spring Initializr在http://start.spring.io/创建一个maven项目,这是一个在线Spring Boot应用程序生成器。

按照上图创建一个打包结构。

pom.xml文件

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>net.guides.springboot2</groupId>
  6. <artifactId>spring-propertysource-example</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <packaging>jar</packaging>
  9. <name>spring-propertysource-example</name>
  10. <description>Demo project for Spring Boot</description>
  11. <parent>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-parent</artifactId>
  14. <version>2.0.5.RELEASE</version>
  15. <relativePath/> <!-- lookup parent from repository -->
  16. </parent>
  17. <properties>
  18. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  19. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  20. <java.version>1.8</java.version>
  21. </properties>
  22. <dependencies>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter</artifactId>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.springframework.boot</groupId>
  29. <artifactId>spring-boot-starter-test</artifactId>
  30. <scope>test</scope>
  31. </dependency>
  32. </dependencies>
  33. <build>
  34. <plugins>
  35. <plugin>
  36. <groupId>org.springframework.boot</groupId>
  37. <artifactId>spring-boot-maven-plugin</artifactId>
  38. </plugin>
  39. </plugins>
  40. </build>
  41. </project>

创建一个config.properties文件

让我们在classpath中创建一个config.properties文件,我们将使用@PropertySource注解来读取一个属性文件,并用@Value和Environment.

  1. jdbc.driver=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql://localhost:3306/dev_db
  3. jdbc.username=root
  4. jdbc.password=root

来显示值。

创建DataSourceConfig.java文件

  1. package net.guides.springboot2.springpropertysourceexample;
  2. public class DataSourceConfig {
  3. private String driver;
  4. private String url;
  5. private String username;
  6. private String password;
  7. @Override
  8. public String toString()
  9. {
  10. return "DataSourceConfig [driver=" + driver + ", url=" + url + ", username=" + username + "]";
  11. }
  12. public String getDriver()
  13. {
  14. return driver;
  15. }
  16. public void setDriver(String driver)
  17. {
  18. this.driver = driver;
  19. }
  20. public String getUrl()
  21. {
  22. return url;
  23. }
  24. public void setUrl(String url)
  25. {
  26. this.url = url;
  27. }
  28. public String getUsername()
  29. {
  30. return username;
  31. }
  32. public void setUsername(String username)
  33. {
  34. this.username = username;
  35. }
  36. public String getPassword()
  37. {
  38. return password;
  39. }
  40. public void setPassword(String password)
  41. {
  42. this.password = password;
  43. }
  44. }

创建 ProperySourceDemo.java 文件

  1. package net.guides.springboot2.springpropertysourceexample;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.beans.factory.InitializingBean;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.context.annotation.PropertySource;
  9. import org.springframework.core.env.Environment;
  10. @Configuration
  11. @PropertySource("classpath:config.properties")
  12. public class ProperySourceDemo implements InitializingBean {
  13. private static final Logger LOGGER = LoggerFactory.getLogger(ProperySourceDemo.class);
  14. @Value("${jdbc.driver}")
  15. private String driver;
  16. @Value("${jdbc.url}")
  17. private String url;
  18. @Value("${jdbc.username}")
  19. private String username;
  20. @Value("${jdbc.password}")
  21. private String password;
  22. @Autowired
  23. Environment env;
  24. @Override
  25. public void afterPropertiesSet() throws Exception {
  26. LOGGER.info(driver);
  27. LOGGER.info(url);
  28. LOGGER.info(password);
  29. LOGGER.info(username);
  30. setDatabaseConfig();
  31. }
  32. private void setDatabaseConfig() {
  33. DataSourceConfig config = new DataSourceConfig();
  34. config.setDriver(env.getProperty("jdbc.driver"));
  35. config.setUrl(env.getProperty("jdbc.url"));
  36. config.setUsername(env.getProperty("jdbc.username"));
  37. config.setPassword(env.getProperty("jdbc.password"));
  38. System.out.println(config.toString());
  39. }
  40. }

The Application.java File

这个spring boot应用程序有一个名为Application.java的入口点Java类,其中有一个公共静态void main(String[] args)方法,你可以运行它来启动应用程序。

  1. package net.guides.springboot2.springpropertysourceexample;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class Application {
  6. public static void main(String[] args) {
  7. SpringApplication.run(Application.class, args);
  8. }
  9. }

@SpringBootApplication是一个方便的注解,添加了以下所有内容。

@Configuration 将该类标记为应用程序上下文的Bean定义的来源。
@EnableAutoConfiguration告诉Spring Boot开始根据classpath设置、其他bean和各种属性设置来添加bean。

通常你会为Spring MVC应用添加@EnableWebMvc,但Spring Boot在classpath上看到spring-webmvc时就会自动添加它。这标志着该应用是一个Web应用,并激活了关键行为,如设置DispatcherServlet
@ComponentScan告诉Spring去寻找hello包中的其他组件、配置和服务,从而使它能够找到控制器。

让我们运行Application.java类并观察控制台的输出。

输出

相关文章