获取默认配置文件的属性

yml文件示例(注意层级)

employee:
  name: 李四
  age: 12
  birthday: 2020-02-12
  hobby:
    - 打球
    - 代码

实体类加上@ConfigurationProperties(prefix = "要获取的对象名")

@ConfigurationProperties(prefix = "employee")

提示 Spring Boot Configuration Annotation Processor not configured

解决办法:

	<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
	</dependency>

User类(对应实体类)

package cn.js.ccit.firstdemo.vo;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author : sheep669
 * @description : TODO
 * @created at 2022/9/6 9:13
 */
@Data
@Component
@ConfigurationProperties(prefix = "employee")
public class User {
    private String name;
    private int age;
    private String birthday;
    private String[] hobby;
}

测试

package cn.js.ccit.firstdemo;

import cn.js.ccit.firstdemo.vo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class FirstDemoApplicationTests {
    @Autowired
    private User user;

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

}

console

···
User(name=李四, age=12, birthday=2020-02-12, hobby=[打球, 代码])

获取自定义配置文件的属性(只能获得properties的文件)

myConfig.properties 自定义的配置文件

user3.name=45

User类

package cn.js.ccit.firstdemo.vo;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author : sheep669
 * @description : TODO
 * @created at 2022/9/6 9:13
 */
@Data
@Component
@PropertySource("classpath:myConfig.properties")
@ConfigurationProperties(prefix = "user3")
public class User {
    private String name;
}

测试

package cn.js.ccit.firstdemo;

import cn.js.ccit.firstdemo.vo.User;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * @author no
 */
@SpringBootApplication
public class FirstDemoApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(FirstDemoApplication.class, args);
        Object user = context.getBean("User1", User.class);
        System.out.println(user);
    }

}

console

···
User(name=45)