spring boot 自定义文件配置

https://blog.csdn.net/ityqing/article/details/80541419 这篇文章讲了自定义属性配置,本篇文件告诉你应该怎么写一个自定义配置文件

其实和自定义属性配置差不多,自定义配置是在spring boot已有的配置文件中添加自定义属性, 而自定义配置文件是自己创建配置文件.

定义一个名为 my.properties 的资源文件,自定义配置文件的命名不强制 application 开头

my.age=22
my.name=Levin

其次定义 MyProperties.java 文件,用来映射我们在 my.properties中的内容。

package com.battcn.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:my.properties")
@ConfigurationProperties(prefix = "my")
public class MyProperties2 {

    private int age;
    private String name;
    // 省略 get set 

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

接下来在 PropertiesController 用来注入 MyProperties2 测试我们编写的代码

@GetMapping("/my")
public MyProperties myProperties() {
    log.info("=================================================================================================");
    log.info(myProperties.toString());
    log.info("=================================================================================================");
    return myProperties;
}



猜你喜欢

转载自blog.csdn.net/ityqing/article/details/80541586