Springboot 就这样读配置,全部都整理好了

今天继续写springboot,整理下零散的知识,系统化的记忆能更好的理解。

springboot 读取配置的几种方式这个大家一般都知道,今天稍微整理下,回头看的时候也有个笔记。

一般我们常用的有几种方式

  • 使用注解@value 读取
  • 读取单个配置文件
  • @ConfigurationProperties
  • Environment获取属性值

下面单个详细说下

1、使用注解@value 读取

这个是最简单的方式,也是最省事的方式,只要在application.properties或者application.yaml中有对应的可以,就可以在bean中使用注解获取配置

配置文件 application.properties里可以

player.name= xiangcai

在代码中可以这么使用,在对象实例化的时候就会注入

@Value("${player.name}") 
public String playerName;

注意:

@Value 没办法注入静态变量。这个时候可以通过set 方法进行注入,在set方法上加入Value注解

@RestController
public class TestController {
    @Value("${player.name}")
    public String playerName;
    public static String staticName;

    @Value("${player.name}")
    public void setStaticName(String playerName) {
        staticName = playerName;
    }

    @GetMapping("/")
    public String test() {
        return staticName;
    }
}

最后提升一下

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {
    String value();
}

我们看下value 注解的代码,可以看到Value是可以用在很多地方,你可以测试下。

2、@ConfigurationProperties

这个注解也是非常好的,可以读取文件的一部分,也是我们最常使用的,自定义一些配置的时候,可以直接将配置映射为对象

application.properties 添加下面的配置

test.name= xiangcai test.age =19

映射的对象定义为

@Configuration
@ConfigurationProperties(prefix = "test")
public class TestConfig {
    private int age;
    private String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

3、读取单个配置文件

一般我们常规开发都是在application.yml(properties)中配置,但是有时候我们想单独起一个配置文件,读取我们自己的配置,这个时候就需要这个了

@propertySource,看注释其实也能看明白,就是Property的地址呗

在项目中创建一个properties,test.properties,内容如下,just for test

player.name= xiangcai22

看下对象的映射

@PropertySource("classpath:test.yml")
@Configuration
@ConfigurationProperties(prefix = "player")
public class PlayerConfig {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

在使用的地方就可以直接使用了。

类似下面这样

@Autowired public PlayerConfig pc;

4、Environment

这个就厉害了,看名字就知道不简单,这个对象可以访问几乎你知道的环境变量

先说下怎么用

第一种实现 EnvironmentAware 接口,获取Environment对象保存使用就行

第二种直接注入,通过Autowired 或者其他的

@RestController
public class TestController implements EnvironmentAware {
    Environment environment;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @GetMapping("/")
    public String test() {
        return environment.getProperty("test.name");
    }
}

最后我们看下都有哪些东西

我们看到我们自定义的properties都解析进去了,通过key 直接访问就行了

总结

1、Environment对象和 @Value在属性多的时候不方便管理,会散落到到处,不太优雅

2、@ConfigurationProperties 直接将配置转换为bean 对象,可以统一管理一族对象,封装起来比较方便。

3、在开发当中建议大家最好将配置封装好,读入对象使用

猜你喜欢

转载自blog.csdn.net/perfect2011/article/details/125594234