SpringBoot-配置⽂件属性注⼊-3种⽅式
配置⽂件:
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);
spring怎么读取配置Environment environment = Environment();
System.out.Property("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();
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。