引用:https://blog.csdn.net/qq_17586821/article/details/79802320

  spring boot允许我们把配置信息外部化。由此,我们就可以在不同的环境中使用同一套程序代码。可以使用属性文件,yaml文件,环境变量,命令行参数来实现配置信息的外部化。可以使用@Value注解来将属性值直接注入到bean里边。也可以使用@ConfigurationProperties注解将属性值注入到结构化的对象里边。

@ConfigurationProperties

  Spring boot 应用中,当使用注解方式定义一个Bean时,同时可以利用@ConfigurationProperties导入外部属性填充到这个Bean的实例。本文通过例子介绍了几种用法可以达到这种效果 :

  • @ConfigurationProperties + @Component 注解到bean定义类上
  • @ConfigurationProperties + @Bean注解在配置类的bean定义方法上
  • @ConfigurationProperties注解到普通类然后通过@EnableConfigurationProperties定义为bean

  例子所采用配置文件
        先在例子项目增加配置文件 src/main/resources/application.properties ,其内容如下

section1.name=Tom
section2.name=Jerry
section3.name=Dog

方式1 : @ConfigurationProperties + @Component 注解到bean定义类上类定义为Bean

        // 将类定义为一个bean的注解,比如 @Component,@Service,@Controller,@Repository
// 或者 @Configuration
@Component
// 表示使用配置文件中前缀为 section1 的属性的值初始化该bean定义产生的的bean实例的同名属性
// 在使用时这个定义产生的bean时,其属性 name 会是 Tom
@ConfigurationProperties(prefix = "section1")
public class Bean1 {
public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} private String name;
}

方式2 : @ConfigurationProperties + @Bean注解在配置类的bean定义方法上Bean来自一个普通类

        // 这是一个一般java类,POJO,没有任何注解
public class Bean2 {
public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} private String name;
}

  使用@Bean注解将一个配置类的方法定义为一个bean
        在项目的某个@Configuration配置类中通过@Bean注解在某个方法上将上面的POJO类定义为一个bean,并使用配置文件中相应的属性初始化该bean的属性。
        这里所说的@Configuration配置类可以是直接通过@Configuration注解的配置类,也可以是隐含使用了@Configuration注解的类,比如下面的例子中,@SpringBootApplication隐含了@Configuration。

        // 声明为Spring boot 应用,隐含了注解@Configuration
@SpringBootApplication
public class Application {
// @Bean 注解在该方法上定义一个bean,这种基于方法的Bean定义不一定非要出现在
// @SpringBootApplication 注解的类中,而是出现在任何@Configuration注解了
// 的类中都可以
@Bean
// 使用配置文件中前缀为section2的属性的值初始化这里bean定义所产生的bean实例的同名属性,
// 在使用时这个定义产生的bean时,其属性 name 会是 Jerry
@ConfigurationProperties(prefix = "section2")
public Bean2 bean2() {
// 注意,这里的 Bean2 是上面所示的一个POJO类,没有任何注解
return new Bean2();
} public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}

方式3 : @ConfigurationProperties注解到普通类然后通过@EnableConfigurationProperties定义为bean

  注解一个普通类的属性将会来自外部属性文件

        // 该注解声明如果该类被定义为一个bean,则对应的bean实例的属性值将来自配置文件中前缀为
// section3的同名属性。但是这个注解本身并不会导致该类被作为一个bean注册
@ConfigurationProperties(prefix = "section3")
public class Bean3 {
public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} private String name;
}

使用@EnableConfigurationProperties将上述类定义为一个bean

        @SpringBootApplication
// 该注解会将类Bean3作为一个bean定义注册到bean容器,而类Bean3上的注解
// @ConfigurationProperties(prefix = "section3")会导致目标bean
// 实例的属性值使用配置文件中前缀为section3的同名属性值来填充,也就是目标
// bean的属性name的值会是Dog
@EnableConfigurationProperties({Bean3.class})
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}

注意重点:

  • 使用@ConfigurationProperties,在这种绑定中,getter 和 setter 方法是强制的,因为这里的绑定是通过标准的Java Bean属性绑定,但是也有例外。
  • 属性配置类的属性名和配置文件中配置信息是对应的(这里的对应并不是要求一模一样,只要能转换成功,就算对应,比如下划线语法、驼峰语法等都能接受)

@Value

  • @Value+ @Component 注解到bean定义类上
  • @Value+ @Bean注解在配置类的bean定义方法上

实现方式同上只是要写全对应的名

  配置文件

book.author=onlymate
book.name=Java is s magic

对应的bean

@Bean
//@Component
@PropertySource("classpath:files/el.properties")
public class CustomElConfig {
//注入普通字符串
@Value("I Love YOU!")
private String normal;
//注入操作系统属性
@Value("#{systemProperties['os.name']}")
private String osName;
//注入表达式结果
@Value("#{T(java.lang.Math).random()*100.0}")
private double randomNumber;
//注入其他的bean属性
@Value("#{customElBean.another}")
private String fromAnother;
//注入文件资源
@Value("classpath:files/test.txt")
private Resource testFile;
//注入网址资源
@Value("http://www.baidu.com")
private Resource testUrl;
//注入配置文件
@Value("${book.name}")
private String bookNmame;
@Value("${book.author}")
private String bookAuthor;
//注入环境
@Autowired
private Environment environment; @Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigure(){
return new PropertySourcesPlaceholderConfigurer();
} public void outputResource(){
try {
System.out.println(normal);
System.out.println(osName);
System.out.println(randomNumber);
System.out.println(fromAnother);
System.out.println(IOUtils.toString(testFile.getInputStream(), Charset.defaultCharset()));
System.out.println(IOUtils.toString(testUrl.getInputStream(), Charset.defaultCharset()));
System.out.println(bookNmame);
System.out.println(environment.getProperty("book.author")); }catch (Exception e){
e.printStackTrace();
System.out.println(e);
}
} }

这里不需要写出set、get方法,属性名也任意,只要@Value("${book.author}")里面的key要对应配置文件中的key

Spring Boot实践——用外部配置填充Bean属性的几种方法的更多相关文章

  1. Spring Boot 支持多种外部配置方式

    Spring Boot 支持多种外部配置方式 http://blog.csdn.net/isea533/article/details/50281151 这些方式优先级如下: 命令行参数 来自java ...

  2. Spring Boot(三):RestTemplate提交表单数据的三种方法

    http://blog.csdn.net/yiifaa/article/details/77939282 ********************************************** ...

  3. Spring Boot 自定义kafka 消费者配置 ContainerFactory最佳实践

    Spring Boot 自定义kafka 消费者配置 ContainerFactory最佳实践 本篇博文主要提供一个在 SpringBoot 中自定义 kafka配置的实践,想象这样一个场景:你的系统 ...

  4. Spring Boot实践——AOP实现

    借鉴:http://www.cnblogs.com/xrq730/p/4919025.html     https://blog.csdn.net/zhaokejin521/article/detai ...

  5. 学记:为spring boot写一个自动配置

    spring boot遵循"约定优于配置"的原则,使用annotation对一些常规的配置项做默认配置,减少或不使用xml配置,让你的项目快速运行起来.spring boot的神奇 ...

  6. Spring Boot之实现自动配置

    GITHUB地址:https://github.com/zhangboqing/springboot-learning 一.Spring Boot自动配置原理 自动配置功能是由@SpringBootA ...

  7. Spring Boot实践——Spring Boot 2.0 新特性和发展方向

    出自:https://mp.weixin.qq.com/s/EWmuzsgHueHcSB0WH-3AQw 以Java 8 为基准 Spring Boot 2.0 要求Java 版本必须8以上, Jav ...

  8. Spring Boot实践——Spring AOP实现之动态代理

    Spring AOP 介绍 AOP的介绍可以查看 Spring Boot实践——AOP实现 与AspectJ的静态代理不同,Spring AOP使用的动态代理,所谓的动态代理就是说AOP框架不会去修改 ...

  9. 【spring boot】spring boot中使用定时任务配置

    spring boot中使用定时任务配置 =============================================================================== ...

随机推荐

  1. dbt 包管理

    dbt 可以方便的支持基于git 的包管理 依赖申明 位置 dbt_project.yml 中的repositories 或者使用packages.yaml 格式 dbt_project.yml: r ...

  2. 如何取出word文档里的图片

    在生活当中,Word办公是必不可少的.但是在工作中也会遇到一些麻烦,比如说如何取出word文档里的图片呢?有的人会通过复制粘贴,通过画图保存,可是这种方法未免太繁琐了吧.下面我就来分享一下我的经验. ...

  3. 49个你应该了解的Android Studio技巧、插件与资源 http://www.apkbus.com/blog-822721-72630.html (出处: 安卓巴士 - 安卓开发 - Android开发 - 安卓 - 移动互联网门户)

    49个你应该了解的Android Studio技巧.插件与资源http://www.apkbus.com/blog-822721-72630.html(出处: 安卓巴士 - 安卓开发 - Androi ...

  4. Mybatis连接Oracle实现增删改查实践

    1. 首先要在项目中增加Mybatis和Oracle的Jar文件 这里我使用的版本为ojdbc7 Mybatis版本为:3.2.4 2. 在Oracle中创建User表 create table T_ ...

  5. Qt常用类及类方法简介之 QAction类

    1.QAction::QAction ( const QString & text, QObject * parent )    QAction类的构造函数之一,利用text,parent创建 ...

  6. Find substring with K-1 distinct characters

    参考 Find substring with K distinct characters Find substring with K distinct characters(http://www.cn ...

  7. 本地环境 XAMPP+phpStorm+XDebug+chrome配置和断点调试 注册方法

    我的安装环境:XAMPP版本号V3.1.0 ;phpStorm版本8.0.3;windowsxp 32bit.您老人家先过目一下,不然怕影响意义. XAMPP.phpStorm 都直接安装在了D盘根目 ...

  8. Spring MVC 原生API

    原生API: Servlet环境中一些有用的对象: HttpServletRequest HttpServletResponse HttpSession Reader Writer InputStre ...

  9. 解决“Can't bind to local 8630 for debugger”错误--查杀多余进程

    Can't bind to local 8630 for debugger 表明本地8630端口被占用 1.Windows平台 在windows命令行窗口下执行: 1.查看所有的端口占用情况 C:\& ...

  10. 《Linux内核精髓:精通Linux内核必会的75个绝技》一HACK #19 ext4的调整

    HACK #19 ext4的调整 本节介绍可以从用户空间执行的ext4调整.ext4在sysfs中有一些关于调整的特殊文件(见表3-6).使用这些特殊文件,就不用进行内核编译.重启,直接从用户空间确认 ...