我们在这里研究的是以yml配置文件值注入的问题:

Person:
lastName: 张三
age: 23
boss: false
birth: 2018-10-11
maps: {k1: v1,k2: v2}
lists:
- pig
- dog
dog:
name: 半半
age: 1

定义了一个Person的实体类:

package com.example.demo.entity;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 将配置文件中配置的属性值映射到组件中
* @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;
@Override
public String toString() {
return "Person{" +
"lastName='" + lastName + '\'' +
", age=" + age +
", boss=" + boss +
", birth=" + birth +
", maps=" + maps +
", lists=" + lists +
", dog=" + dog +
'}';
}

再定义一个dog的实体类

package com.example.demo.entity;
public class Dog {
private String name;
private Integer age; @Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
set/get方法......

再定义一个测试类:

package com.example.demo;
import com.example.demo.entity.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* springBoot测试
* 可以在测试期间可以很方便的类似编码一样进行自动注入等容器的功能
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Autowired
Person person;
@Test
public void contextLoads() {
System.out.println(person);
}
}

测试结果:

重点:

2、@Value获取值和@ConfigurationProperties获取值比较

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

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

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

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

所以我们也可以利用@Value()进行赋值:

@Componentpublic class Person {
//lastName必须是邮箱格式@Value("${person.last-name}")
private String lastName;
@Value("#{11*2}")
private Integer age;
@Value("true")
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;

在配置文件值注入的时候进行数据校验:

@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
//lastName必须是邮箱格式
@Email
private String lastName;
private Integer age;private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
private Boolean boss;

3、@PropertySource&@ImportResource&@Bean

@PropertySource:加载指定的配置文件,将配置文件中配置的每一个属性的值,映射到这个组件中
@ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定,
prefix = "person":配置文件中哪个下面的所有属性进行一一映射只有这个组件是容器中的组件,才能

容器提供的@ConfigurationProperties功能,@ConfigurationProperties(prefix = "person")默认从全局

配置文件中获取值。

@PropertySource(value = {"classpath:person.properties"})
@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;
}
set/get方法.....

@ImportResource:导入Spring的配置文件,让配置文件里面的内容生效;

Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别;

想让Spring的配置文件生效,加载进来;@ImportResource标注在一个配置类上

@ImportResource(locations = {"classpath:beans.xml"})
导入Spring的配置文件让其生效

SpringBoot推荐给容器中添加组件的方式;推荐使用全注解的方式

1、配置类@Configuration

2、使用@Bean给容器中添加组件

@Configuration
public class MyAppConfig {
//将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
@Bean
public HelloService helloServicfun(){
System.out.println("配置类@Bean给容器中添加组件了...");
return new HelloService();
}
}

SpingBoot之配置文件的值注入问题的更多相关文章

  1. spring 读取配置文件,将值注入到静态字段

    resources/config/config-dev.properties es.ip.node=xxxxxxxcluster.name=xxxxxxxclient.transport.sniff= ...

  2. Spring Boot之配置文件值注入(@ConfigurationProperties)

    前言:Spring Boot配置文件值的注入有两种方式,分别是 @ConfigurationProperties @Value 这里我们使用第一种 首先我们创建一个application.yml文件, ...

  3. 3springboot:springboot配置文件(配置文件、YAML、属性文件值注入<@Value、@ConfigurationProperties、@PropertySource,@ImportResource、@Bean>)

    1.配置文件: springboot默认使用一个全局配置文件 配置文件名是固定的   配置文件有两种(开头均是application,主要是文件的后缀): ->application.prope ...

  4. 结合SpEL使用@Value-基于配置文件或非配置的文件的值注入-Spring Boot

    本文主要介绍Spring @Value 注解注入属性值的使用方法的分析,文章通过示例代码非常详细地介绍,对于每个人的学习或工作都有一定的参考学习价值 在使用spring框架的项目中,@Value是经常 ...

  5. SpringBoot基础学习(二) SpringBoot全局配置文件及配置文件属性值注入

    全局配置文件 全局配置文件能够对一些默认配置值进行修改.SpringBoot 使用一个名为 application.properties 或者 application.yaml的文件作为全局配置文件, ...

  6. Spring 设值注入 构造注入 p命名空间注入

    注入Bean属性---构造注入配置方案 在Spring配置文件中通过<constructor-arg>元素为构造方法传参 注意: 1.一个<constructor-arg>元素 ...

  7. Spring接口编程_设值注入和构造注入

    说明: UserManagerImp是设值注入,UserManagerImp2是构造注入 接口不注入,也就是在Spring配置文件中没有接口的<bean>,但是定义的时候是用接口 priv ...

  8. spring 运行时属性值注入

    继续spring学习,今天介绍两种外部属性值注入的方式.当你需要读取配置信息时,可以快速读取. 开始之前先创建属性文件site.properties,放在classpath下面 #数据库配置 ### ...

  9. 【Spring学习笔记-2.1】Spring的设值注入和构造注入

    设值注入: 先通过无参数的构造函数创建一个Bean实例,然后调用对应的setter方法注入依赖关系: 配置文件: <?xml version="1.0" encoding=& ...

随机推荐

  1. crawlspider的源码学习

    Spider基本上能做很多事情了,但是如果你想爬取全站的话,可能需要一个更强大的武器.CrawlSpider基于Spider,但是可以说是为全站爬取而生.CrawlSpiders是Spider的派生类 ...

  2. python大战机器学习——模型评估、选择与验证

    1.损失函数和风险函数 (1)损失函数:常见的有 0-1损失函数  绝对损失函数  平方损失函数  对数损失函数 (2)风险函数:损失函数的期望      经验风险:模型在数据集T上的平均损失 根据大 ...

  3. 文件系统满的话(filesystem full),该如何处理。(du and ls)

    #!/bin/bash function ergodic(){ ` do "/"$file ] then ergodic $"/"$file else loca ...

  4. linux 编程笔记1 crusher for linux

    1.反显示字符crusher #include <stdio.h> int main (int argc, char *argv[]) { printf("\033[7m mor ...

  5. sqoop导出hive数据到mysql错误: Caused by: java.lang.RuntimeException: Can't parse input data

    Sqoop Export数据到本地数据库时出现错误,命令如下: sqoop export \ --connect 'jdbc:mysql://202.193.60.117/dataweb?useUni ...

  6. 3 - Selenium元素定位和操作

    3.1定位 <button id="gbqfba" aria-label="Google Search" name="btnK" cl ...

  7. pat1064. Complete Binary Search Tree (30)

    1064. Complete Binary Search Tree (30) 时间限制 100 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHE ...

  8. C 碎片一 计算机知识

    一.计算机知识 1, 计算机组成及工作原理 计算机是硬件和软件的结合体.硬件由主机箱和外部设备组成,主机主要包括CPU.内存.主板.硬盘.光驱.各种扩展卡.连接线.电源等:外部设备包括鼠标.键盘等.软 ...

  9. 一张图掌握移动Web前端所有技术(大前端、工程化、预编译、自动化)

    你要的移动web前端都在这里! 大前端方向:移动Web前端.Native客户端.Node.js. 大前端框架:React.Vue.js.Koa  跨终端技术:HTML 5.CSS 3.JavaScri ...

  10. Sometimes it takes going through something so awful to realize the beauty that is out there in this world.

    Sometimes it takes going through something so awful to realize the beauty that is out there in this ...