在设计自己的Yml配置时会发现,@Configuration和@Value混用会出现参数报空的情况,
解决方案:从Environment对象直接获取参数,或者使用@ConfigurationProperties注解

Yml配置

mytest:
  user:
    name: test
    age: 22
    phone: 13533559797

获取配置参数

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * @author Mr.css on 2018/8/2.
 */
@Configuration
@ConfigurationProperties(prefix = "mytest.user")
public class PoolParams {
    private String name;
    private int age;
    private String phone;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

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

获取参数

import com.sea.plugin.bean.PoolParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Mr.css on 2018/8/2.
 */
@Configuration
public class MyPool {
    @Autowired
    PoolParams params;

    /**
     * 使用配置参数,在容器中注册别的Bean
     */
    @Bean("list1")
    public List<PoolParams> print(){
        List<PoolParams> list = new ArrayList<>();
        list.add(params);
        return list;
    }

    /**
     * 直接使用Environment获取配置参数,这种方式简单、直接,但是类型转换要自己处理,
     */
    @Bean("list2")
    public List<PoolParams> example(Environment en){
        PoolParams params = new PoolParams();
        params.setName(en.getProperty("mytest.user.name"));

        List<PoolParams> list = new ArrayList<>();
        list.add(params);
        return list;
    }
}

 

相关文章:

  • 2021-06-23
  • 2021-06-07
  • 2021-08-28
  • 2022-01-09
  • 2022-03-04
  • 2021-08-16
  • 2021-07-09
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-08-30
  • 2021-04-16
  • 2021-11-29
  • 2021-04-11
相关资源
相似解决方案