一、利用Bean注解中的Value(${})注解

@Data
@Component
public class ApplicationProperty {
    @Value("${application.name}")
    private String name;
}
复制代码

该方式可以自动读取当前配置文件appliation.yml 或者application.properties中的配置值

区别在于读取yml文件时候支持中文编码,peoperties需要转码

二、利用@ConfigurationProperties(prefix = "developer")注解

@Data
@ConfigurationProperties(prefix = "developer")
@Component
public class DeveloperProperty {
    private String name;
    private String website;
    private String qq;
    private String phoneNumber;
}
复制代码

该方式直接将当前加载yml配置文件前缀为developer的属性

读取developer.name...

pom文件中引入依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
</dependency>
复制代码

三、前两种读取配置的使用方式

//使用方法
private final ApplicationProperty applicationProperty;
private final DeveloperProperty developerProperty;

@Autowired
    public PropertyController(ApplicationProperty applicationProperty, DeveloperProperty developerProperty) {
        this.applicationProperty = applicationProperty;
        this.developerProperty = developerProperty;
    }

@GetMapping("/property")
    public Dict index() {
        System.out.println("name:"+applicationProperty.getName());
        System.out.println("version:"+applicationProperty.getVersion());
        System.out.println("DevName:"+applicationProperty.getDeveloperName());
    }
复制代码

四、用Hutool的方式读取配置文件(不支持yml格式)

1.用Props的方式读取

static Props props1 = new Props("application.properties",CharsetUtil.CHARSET_UTF_8);
复制代码

2.用Setting的方法读取

static Setting setting = new Setting("application-dev.yml", CharsetUtil.CHARSET_UTF_8,true);
复制代码

3.将配置文件读取

public class Constant {
    
    static Props props1 = new Props("application.properties",CharsetUtil.CHARSET_UTF_8);

    static Setting setting = new Setting("application-dev.properties", CharsetUtil.CHARSET_UTF_8,true);

    public static final String Name ;
    public static final String SettingName ;

    static {
        Name = props.getStr("application.name");
        SettingName = setting.getByGroup("name","application");

    }
}
复制代码

4.使用方式

System.out.println(Constant.DevName+"------"+Constant.DevWebsite);
复制代码

直接用常量类调用该类属性即可使用