Spring Boot 使用@ConfigurationProperties注解获取配置文件中的值

如果在开发的时候,我们往往会动态的配置一些属性,而且这些属性在代码中大量使用,我们可以将这个属性配置到application-development.yml(也可以是其他),然后通过@ConfigurationProperties注解来进行动态配置。

在application-development.yml中配置添加一个属性

test:
  property:
    name: Jeason
    password: 123456

然后我们可以对这个配置进行统一的配置,写一个配置类TestPropertyConfig


@Configuration
public class PropertyTestConfig {

    @Bean
    @ConfigurationProperties(prefix = "test")
    public TestProperties testProperties(){
        return new TestProperties();
    }


    public static class TestProperties{
        Map<String, String> property = new HashMap<String, String>();
        //获取test下面的property 的值然后放在Map中
        public Map<String, String> getProperty() { 
            return this.property;
        }
    }

}

好了,这里我们就将配置中的test这个属性放入了PropertyTestConfig这个配置类中。直接使用@AutoWired 注入
PropertyTestConfig.TestProperties

@Controller
public class TestController {


    @Autowired
    private PropertyTest.TestProperties testProperties;

    @RequestMapping({"/","/index"})
    @ResponseBody
    public String index(){
      String name=testProperties.
      getProperty().get("name");
        return name;
    }

    @RequestMapping("test")
    public String test(){
        return "error";
    }
}

最后将会返回Jeason这个值

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot,可以使用@ConfigurationProperties注解来将配置文件的属性与Java对象进行绑定。这样可以方便地管理应用程序的配置属性。 下面是使用@ConfigurationProperties注解的步骤: 1. 创建一个Java类,并在类上添加@ConfigurationProperties注解。该注解的value属性指定了配置文件的前缀,prefix属性指定了配置文件的属性前缀。例如,如果配置文件的属性为myconfig.name,那么可以将value属性设置为"myconfig"。 ```java @ConfigurationProperties(prefix = "myconfig") public class MyConfigProperties { private String name; // getter和setter方法 } ``` 2. 在配置文件(application.properties或application.yml)定义属性。例如,在application.properties添加以下内容: ``` myconfig.name=bj ``` 3. 在Spring Boot应用程序的主类使用@EnableConfigurationProperties注解来启用@ConfigurationProperties注解。将@ConfigurationProperties注解的类作为参数传递给@EnableConfigurationProperties注解。 ```java @SpringBootApplication @EnableConfigurationProperties(MyConfigProperties.class) public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } } ``` 现在,可以在其他组件注入使用@ConfigurationProperties注解的类,并使用的属性。例如,在一个Service类注入MyConfigProperties类: ```java @Service public class MyService { private final MyConfigProperties configProperties; public MyService(MyConfigProperties configProperties) { this.configProperties = configProperties; } public void printName() { System.out.println("Name: " + configProperties.getName()); } } ``` 这样,就可以在应用程序使用@ConfigurationProperties注解来管理配置属性了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值