配置文件:
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(); } }