Spring Boot 学习笔记,2.3.Spring Boot 配置——加载配置文件@ProertySource和@ImportSource

本文详细介绍了Spring Boot中@PropertySource和@ImportResource的使用。@PropertySource用于加载额外的.properties配置文件,常与@ConfigurationProperties或@Value结合使用,而@ImportResource则用于导入Spring的XML配置文件。通过示例展示了如何在Spring Boot项目中应用这两个注解,并强调了主配置文件的优先级高于@PropertySource指定的配置文件。
摘要由CSDN通过智能技术生成

一、@PropertySource

@PropertySource:加载指定的配置文件,只使用于.properties格式的文件;
@ConfigurationProperties默认是从全局配置文件中获取值的,如果把所有的配置都写在全局配置文件中,就会显得主配置文件内容特别多。所以我们把一些和Spring Boot无关的配置单独放在一个配置文件下,这个时候就需要@PropertySource;
@PropertySource需要与@ConfigurationProperties或则@Value配合使用;
主配置文件application.yml或则application.properties优先级高于@PropertySource指定的配置文件;

  1. 将主配置文件application中person属性注释掉,如果不注释掉,主配置文件中的内容会覆盖掉指定配置文件中的内容;
  2. resource文件夹下新建指定配置文件person.properties
person.last-name=王五
person.age=25
person.boss=true
person.birth=201901/01/05
person.maps.k1=v51
person.maps.k2=v52
person.maps.k3=v53
person.lists=aa,bb,cc
person.dog.name=五花狗
person.dog.age=5

  1. Person类上添加@PropertySource
package cn.springboottest.springboot.bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Email;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 将配置文件中配置的每一个属性值,映射到这个组件中
 * @ConfigurationProperties: 告诉Spring Boot将本类中的所有属性和配置文件中相关的配置进行绑定
 * prefix ="person":配置文件中哪个下面的所有属性进行一一映射
 *
 * 只有这个组件是容器中的组件,才能使用容器提供的@ConfigurationProperties功能
 *
 * @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值;
 *
 *
 */
@PropertySource(value = {
   "classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
   
    /*
    <bean class="cn.springboottest.springboot.bean.Person" >
        <property key="lastName" value="字面量/${key}从环境变量,配置文件中获取值/#{SpEL}"></property>
    </bean>
     */
    //@Value("${person.last-name}")
//    @Email
    private String lastName;
    //@Value("#{11*5}")
    private Integer age;
    //@Value("true")
    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 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值