配置文件:
datasource.username = admin
datasource.url = /hello/world
方式一: @Value
前提:
<!-- JavaBean處理工具包 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
使用:
@Component @Data public class PropertyBean { @Value("${datasource.url}") private String url; @Value("${datasource.username}") private String userName; }
方式二:
前提:
<!-- 支持 @ConfigurationProperties 注解 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>${spring-boot.version}</version>
</dependency>
使用: @ConfigurationProperties
@Component @Configuration @EnableAutoConfiguration public class PropertyBeanUtil { @Bean @ConfigurationProperties(prefix = "datasource") public PropertyBean propertyBean() { return new PropertyBean(); } }
方式三:獲得Environment 的對象
@SpringBootApplication public class SpringBootDemo3Application { public static void main(String[] args) { final ApplicationContext ctx = SpringApplication.run(SpringBootDemo3Application.class, args); Environment environment = ctx.getEnvironment(); System.out.println(environment.getProperty("datasource.username")); } }
擴展:
使用@PropertySource注解加載自定義的配置文件,但該注解無法加載yml配置文件。然后可以使用@Value注解獲得文件中的參數值
/** * 加載properties配置文件,在方法中可以獲取 * abc.properties文件不存在,驗證ignoreResourceNotFound屬性 * 加上encoding = "utf-8"屬性防止中文亂碼,不能為大寫的"UTF-8" */ @Configuration @PropertySource(value = {"classpath:/config/propConfigs.properties","classpath:/config/db.properties"}, ignoreResourceNotFound = true,encoding = "utf-8") public class PropConfig { // PropertySourcesPlaceholderConfigurer這個bean, // 這個bean主要用於解決@value中使用的${…}占位符。 // 假如你不使用${…}占位符的話,可以不使用這個bean。 @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } }
