【Springboot总结】4. 配置文件值注入--配置

本文详细介绍了Spring Boot中配置文件的多种注入方式,包括使用@ConfigurationProperties和@Value注解,以及如何通过@PropertySource和@ImportResource加载特定配置。探讨了各注解的功能差异,如松散绑定、SpEL支持、数据校验和复杂类型封装。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

总结

1. 配置文件值注入到实体对象中 @ConfigurationProperties 、@Value

2. 加载指定的路径下的配置文件 @PropertySource

3. 加载Spring的配置文件 @ImportResource (不推荐)。一般都是@Configuration、@Bean 配置类的方式实现。

 

一、在application.yml中配置

配置文件的值注入到实体类中,需要@Component、@ConfigurationProperties(prefix="xxx")注解。

记得设置中文乱码问题。

1. application.yml

person:
    last-name: pzz
    age: 18
    boss: false
    birth: 2017/12/12
    maps: {k1: v1,k2: 12}
    lists:
      - lisi
      - zhaoliu
    dog:
      name: 小狗
      age: 12

2. JavaBean

(1)Person

package com.bjfu.springboot03.entity;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 将配置文件中配置的每一个属性的值,映射到这个组件中
 * @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;

    public Person(String lastName, Integer age, Boolean boss, Date birth, Map<String, Object> maps, List<Object> lists, Dog dog) {
        this.lastName = lastName;
        this.age = age;
        this.boss = boss;
        this.birth = birth;
        this.maps = maps;
        this.lists = lists;
        this.dog = dog;
    }

    public Person() {
    }

    @Override
    public String toString() {
        return "Person{" +
                "lastName='" + lastName + '\'' +
                ", age=" + age +
                ", boss=" + boss +
                ", birth=" + birth +
                ", maps=" + maps +
                ", lists=" + lists +
                ", dog=" + dog +
                '}';
    }

    public String getLastName() {
        return lastName;
    }

    public Integer getAge() {
        return age;
    }

    public Boolean getBoss() {
        return boss;
    }

    public Date getBirth() {
        return birth;
    }

    public Map<String, Object> getMaps() {
        return maps;
    }

    public List<Object> getLists() {
        return lists;
    }

    public Dog getDog() {
        return dog;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public void setBoss(Boolean boss) {
        this.boss = boss;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public void setMaps(Map<String, Object> maps) {
        this.maps = maps;
    }

    public void setLists(List<Object> lists) {
        this.lists = lists;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }
}

(2)Dog

package com.bjfu.springboot03.entity;

public class Dog {

    private String name;
    private Integer age;

    public Dog() {

    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public Dog(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

3. 测试

package com.bjfu.springboot03;

import com.bjfu.springboot03.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;


@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot03ApplicationTests {

	@Autowired
	Person person;

	@Test
	public void contextLoads() {
		System.out.println(person);
	}

}

4. 结果

 

二、在application.properties中配置

 

1. application.properties

2.调整编码

3. 测试结果

 

三、@Value

从配置文件中获取值的方式除了@ConfigurationProperties,还有@Value

1. 字面量

2.  ${ key}

3. SpEL表达式

 

四、二者比较

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

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

 

1. 松散绑定

     

     @Value必须要求配置文件的key要与获取值时的key保持完全一致,而@ConfigurationProperties可以松散,也就是可以不完全一致!

2. SpEL

            

@ConfigurationProperties对于SpEL表达式不支持

3. 数据验证

    @Validated与 @Email 验证 邮件的格式


@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {

    /**
     * <bean class="Person">
     *      <property name="lastName" value="字面量/${key}从环境变量、配置文件中获取值/#{SpEL}"></property>
     * <bean/>
     */

   //lastName必须是邮箱格式
    @Email
    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;

总结

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

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

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

 

五、@PropertySource

@PropertySource:加载指定的配置文件,而不是默认去加载全局的配置文件application.yml.

1. 配置文件

 

2. 实体类

/**
 * 将配置文件中配置的每一个属性的值,映射到这个组件中
 * @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;

 

因为之前的配置信息都是放在全局配置文件的,若是配置信息比较多,可能会比较乱!使用该注解可以加载不同路径下的配置文件。这样会比较有条理。

 

六、@ImportResource

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

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

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

 

1. 编写bean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean>
</beans>

2. 把注解放在主配置类上

3. 测试

查看ioc容器中是否存在id等于helloService的对象!也就变相的证明了配置是否生效!

 

当然上面注入bean的方式是不推荐的,现在都是全注解开发。全注解的开发就不需要@ImportResource注解了

1、配置类@Configuration------>Spring配置文件

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

/**
 * @Configuration:指明当前类是一个配置类;就是来替代之前的Spring配置文件
 *
 * 在配置文件中用<bean><bean/>标签添加组件
 *
 */
@Configuration
public class MyAppConfig {

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值