【springboot】在配置文件中为对象属性赋值

1. 使用yaml配置文件

创建一个Person对象,如下

@Component
@ConfigurationProperties(prefix = "person")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
    private String name;
    private int age;
    private List<String> friends;

}

@ConfigurationProperties(prefix = "person"):从配置文件中读取以person开头的属性,映射到对象属性

只有容器中的组件才能使用上述注解,所以要加上@Component

类比spring的配置文件:

@Component相当于是bean标签

@ConfigurationProperties相当于是bean标签内的属性注入property

配置文件application.yaml内容如下

person:
  name: "zhangsan"
  age: 18
  friends:
    - "lisi"
    - "wangwu"

测试

@SpringBootTest
class HelloworldApplicationTests {

    /**
     * 自动注入
     */
    @Autowired
    Person person;

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

}

运行结果

Person(name=zhangsan, age=18, friends=[lisi, wangwu])

这样就实现了类似spring配置文件中使用bean创建对象


2. 使用properties配置文件

application.properties内容如下,将yaml中的内容注释,测试结果同上

# 设置对象属性的值
person.name=zhangsan
person.age=18
person.friends=lisi,wangwu

也可以在属性上使用spring的@Value注解为对象属性赋值,值可以从配置文件中取(使用${}

以properties配置文件为例,如

@Component
// @ConfigurationProperties(prefix = "person")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
    @Value("zhangsan")
    private String name;
    @Value("${person.age}")
    private int age;
    private List<String> friends;

}

这里没有对friends属性赋值,结果应为null

Person(name=zhangsan, age=18, friends=null)

注意:@Value不支持数据校验,不支持Map等较复杂的类型


3. 自定义配置文件

@ConfigurationProperties(prefix = "person")的作用是从配置文件中读取以person开头的property,默认从主配置文件中读取

但是将对象的属性值写在主配置文件当中不是很好,可以使用@PropertySource(value = "classpath:person.properties")指定配置文件

当使用@PropertySource时,其实依然会优先从主配置文件中读取,当没有找到相关信息后,才到指定的配置文件中读取。所以在使用@PropertySource时,就不要在主配置文件中写相关内容了

@PropertySource的value属性是一个数组,因此可以指定多个配置文件,但要注意,前面要加上classpath:,不然会出错

package com.yimin.helloworld.bean;

import java.util.List;

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 lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Component
@ConfigurationProperties(prefix = "person")
@PropertySource(value = "classpath:person.properties")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
    private String name;
    private int age;
    private List<String> friends;

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容