方案1:@ConfigurationProperties+@Component

 定义spring的一个实体bean装载配置文件信息,其它要使用配置信息是注入该实体bean

 /**
* 将配置文件中配置的每一个属性的值,映射到这个组件中
* @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
* prefix = "person":配置文件中哪个下面的所有属性进行一一映射
*
* 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;
*
*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {

private String lastName;
private Integer age;
private Boolean boss;
private Date birth;

private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;

方案2:@Bean+@ConfigurationProperties

我们还可以把@ConfigurationProperties还可以直接定义在@bean的注解上,这是bean实体类就不用@Component和@ConfigurationProperties了,这边是Boot的动态数据源切换的类。

 package com.topcheer.oss.base.datasource;

import com.alibaba.druid.pool.DruidDataSource;

import com.xiaoleilu.hutool.crypto.symmetric.SymmetricAlgorithm;
import com.xiaoleilu.hutool.crypto.symmetric.SymmetricCrypto;
import com.xiaoleilu.hutool.util.CharsetUtil;
import com.xiaoleilu.hutool.util.HexUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class UmspscDataSource extends DruidDataSource {

private static final long serialVersionUID = 4766401181052251539L;

private String passwordDis; /**
* 密匙
*/
private final static String Pkey ="1234565437892132"; @Override
public String getPassword() {
if(passwordDis != null && passwordDis.length() > 0) {
return passwordDis;
}
String encPassword = super.getPassword();
if(null == encPassword) {
return null;
}
log.info("数据库密码加解密,{" + encPassword + "}");
try {
// 密文解密,解密方法可以修改
String key = HexUtil.encodeHexStr(Pkey);
SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key.getBytes());
passwordDis = aes.decryptStr(encPassword, CharsetUtil.CHARSET_UTF_8);
return passwordDis;
} catch (Exception e) {
log.error("数据库密码解密出错,{"+encPassword + "}");
//log.error(LogUtil.e(e));
//throw new Exception("数据库密码解密失败!", e);
return null;
}
}

}
 @Bean(name = "systemDataSource")
@ConfigurationProperties(ignoreUnknownFields = false, prefix = "spring.datasource.system")
public DataSource systemDataSource() {
return new UmspscDataSource();
}

@Bean(name = "secondDataSource")
@ConfigurationProperties(ignoreUnknownFields = false, prefix = "spring.datasource.second")
public DataSource secondDataSource() {
return new UmspscDataSource();
} @Bean(name="systemJdbcTemplate")
public JdbcTemplate systemJdbcTemplate(
@Qualifier("systemDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
} @Bean(name="secondJdbcTemplate")
public JdbcTemplate secondJdbcTemplate(
@Qualifier("secondDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}

方案3:@ConfigurationProperties + @EnableConfigurationProperties

我们和上面例子一样注解属性,然后用 Spring的@Autowire来注入 mail configuration bean:

 package com.dxz.property;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(locations = "classpath:mail.properties", ignoreUnknownFields = false, prefix = "mail")
public class MailProperties {
private String host;
private int port;
private String from;
private String username;
private String password;
private Smtp smtp;

// ... getters and setters
public String getHost() {
return host;
}

public void setHost(String host) {
this.host = host;
}

public int getPort() {
return port;
}

public void setPort(int port) {
this.port = port;
}

public String getFrom() {
return from;
}

public void setFrom(String from) {
this.from = from;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public Smtp getSmtp() {
return smtp;
}

public void setSmtp(Smtp smtp) {
this.smtp = smtp;
} @Override
public String toString() {
return "MailProperties [host=" + host + ", port=" + port + ", from=" + from + ", username=" + username
+ ", password=" + password + ", smtp=" + smtp + "]";
}

public static class Smtp {
private boolean auth;
private boolean starttlsEnable;

public boolean isAuth() {
return auth;
}

public void setAuth(boolean auth) {
this.auth = auth;
}

public boolean isStarttlsEnable() {
return starttlsEnable;
}

public void setStarttlsEnable(boolean starttlsEnable) {
this.starttlsEnable = starttlsEnable;
}

}
}

启动类及测试类:

 package com.dxz.property;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
@EnableConfigurationProperties(MailProperties.class)
public class TestProperty1 {

@Autowired
private MailProperties mailProperties; @RequestMapping(value = "/hello", method = RequestMethod.GET)
@ResponseBody
public String hello() {
System.out.println("mailProperties" + mailProperties);
return "hello world";
}

public static void main(String[] args) {
//SpringApplication.run(TestProperty1.class, args);
new SpringApplicationBuilder(TestProperty1.class).web(true).run(args);

}
}

结果:

请注意@EnableConfigurationProperties注解。该注解是用来开启对@ConfigurationProperties注解配置Bean的支持。也就是@EnableConfigurationProperties注解告诉Spring Boot 能支持@ConfigurationProperties。如果不指定会看到如下异常:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.dxz.property.MailProperties] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

注意: 还有其他办法 (Spring Boot 总是有其他办法!) 让@ConfigurationProperties beans 被添加 – 用@Configuration或者 @Component注解, 这样就可以在 component scan时候被发现了。

  @ConfigurationProperties @Value
功能 批量注入配置文件中的属性 一个个指定
松散绑定(松散语法) 支持 不支持
SpEL 不支持 支持
JSR303数据校验 支持 不支持
复杂类型封装 支持 不支持

配置文件yml还是properties他们都能获取到值;

如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value;

如果说,我们专门编写了一个javaBean来和配置文件进行映射,我们就直接使用@ConfigurationProperties;

SpringBoot注入配置文件的3种方法的更多相关文章

  1. Springboot读取配置文件的两种方法

    第一种: application.yml配置中的参数: zip: Hello Springboot 方法读取: @RestController public class ControllerTest ...

  2. java读取配置文件的几种方法

    java读取配置文件的几种方法 原文地址:http://hbcui1984.iteye.com/blog/56496         在现实工作中,我们常常需要保存一些系统配置信息,大家一般都会选择配 ...

  3. Spring---加载配置文件的几种方法(org.springframework.beans.factory.BeanDefinitionStoreException)

    Spring中的几种容器都支持使用xml装配bean,包括:XmlBeanFactory ,ClassPathXmlApplicationContext ,FileSystemXmlApplicati ...

  4. SpringBoot 常用读取配置文件的 3 种方法!

    我们在SpringBoot框架进行项目开发中该如何优雅的读取配置呢?或者说对于一些List或者Map应该如何配置呢? 本篇主要解决如下几个问题: 1.Spring Boot有哪些常用的读取配置文件方式 ...

  5. java读取.properties配置文件的几种方法

    读取.properties配置文件在实际的开发中使用的很多,总结了一下,有以下几种方法(仅仅是我知道的):一.通过jdk提供的java.util.Properties类.此类继承自java.util. ...

  6. flask配置文件的几种方法

    配置文件的参数 flask中的配置文件是一个flask.config.Config对象(继承字典),默认配置为: { 'DEBUG': get_debug_flag(default=False), 是 ...

  7. spring注入bean的三种方法

    在Spring的世界中, 我们通常会利用bean config file 或者 annotation注解方式来配置bean. 在第一种利用bean config file(spring xml)方式中 ...

  8. 【转载】java读取.properties配置文件的几种方法

    读取.properties配置文件在实际的开发中使用的很多,总结了一下,有以下几种方法(仅仅是我知道的):一.通过jdk提供的java.util.Properties类.此类继承自java.util. ...

  9. flask加载配置文件的三种方法

    1.第一种方法也是我们最长用到的,包括我们项目中也是采用第一种的方法,加载配置文件 配置信息全部写在config.py里面,在主app.py的文件中写入 import config app.confi ...

随机推荐

  1. Spring boot 梳理 - 在bean中使用命令行参数-自动装配ApplicationArguments

    If you need to access the application arguments that were passed to SpringApplication.run(…​), you c ...

  2. 使用maven开发javaweb项目

    想重新学习一下java web的知识,之前也学习过一些但是也没有用在开发中所以也忘的七七八八了,因为从事Android开发免不了要与服务器打交道,有时候想自己写一个小DEMO需要服务器的时候感觉真是很 ...

  3. Mycat 配置文件rule.xml

    rule.xml配置文件定义了我们对表进行拆分所涉及到的规则定义.我们可以灵活的对表使用不同的分片算法,或者对表使用相同的算法但具体的参数不同. 该文件里面主要有tableRule和function这 ...

  4. 正睿OI国庆day1

    正睿OI国庆day1 T1 \[ S_n=1*S_{n-1}+1*F_{n-1}+1*F_{n-2}+1*f_{n-1}+1*f_{n-2} \] \[ F_{n}=0*S_{n-1}+1*F_{n- ...

  5. Python基础(十八)

    今日主要内容 包 一.包 (一)什么是包 只要是含有__init__.py文件的文件夹就是一个包 包的本质其实就是一个文件夹,利用包将不同功能的模块组织起来,以此来提高程序的结构性和可维护性 包是用来 ...

  6. Fast Earth - 文本 绘制,如何实现三维空间中绘制屏幕大小的文字?

    如题:先上一张图,在说是如何实现的 实现上图效果,有如下三种方式: 1. 屏幕坐标绘制点要素,即将经纬度坐标转换成屏幕坐标方式绘制,大多数GIS系统都是采用这种方式: 优点:实现方式简单,效果较好 缺 ...

  7. LitePal的存储操作

    传统的存储数据方式   其实最传统的存储数据方式肯定是通过SQL语句拼接字符串来进行存储的,不过这种方式有点过于“传统”了,今天我们在这里就不讨论这种情况.实际上,Android专门提供了一种用于存储 ...

  8. 洛谷 1552 [APIO2012]派遣

    题目背景 在一个忍者的帮派里,一些忍者们被选中派遣给顾客,然后依据自己的工作获取报偿. 题目描述 在这个帮派里,有一名忍者被称之为Master.除了Master以外,每名忍者都有且仅有一个上级.为保密 ...

  9. ZGC gc策略及回收过程-源码分析

    源码文件:/src/hotspot/share/gc/z/zDirector.cpp 一.回收策略 main入口函数: void ZDirector::run_service() { // Main ...

  10. java位运算,逻辑运算符

    位运算逻辑运算符包括: 与(&),非(~),或(|),异或(^). &:  条件1&条件2  ,只有条件1和条件2都满足, 整个表达式才为真true,  只要有1个为false ...