配置中的属性占位符 [英] Property placeholder from Configuration

查看:103
本文介绍了配置中的属性占位符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Spring在xml上下文中,我们可以简单地加载如下属性:

With Spring in xml context we can simple load properties like this:

<context:property-placeholder location:"classpath*:app.properties"/>

是否有机会在没有样板的情况下在@Configuration bean(〜来自java代码)中配置相同的属性?

Is there any chance to configure same properties inside @Configuration bean (~ from java code) without boilerplate?

谢谢!

推荐答案

您可以使用注释 @PropertySource 喜欢这个

You can use the annotation @PropertySource like this

@Configuration
@PropertySource(value="classpath*:app.properties")
public class AppConfig {
 @Autowired
 Environment env;

 @Bean
 public TestBean testBean() {
     TestBean testBean = new TestBean();
     testBean.setName(env.getProperty("testbean.name"));
     return testBean;
 }
}

参见: http://static.springsource.org/spring/docs /3.1.x/javadoc-api/org/springframework/context/annotation/PropertySource.html

编辑:如果你使用弹簧靴你可以使用 @ConfigurationProperties 注释将属性文件直接连接到bean属性,如下所示:

if you are using spring boot you can use @ConfigurationProperties annotation to wire the properties file directly to bean properties, like this:

test.properties

test.properties

name=John Doe
age=12

PersonProperties.java

PersonProperties.java

@Component
@PropertySource("classpath:test.properties")
@ConfigurationProperties
public class GlobalProperties {

    private int age;
    private String name;

    //getters and setters
}

source:
https://www.mkyong.com/spring- boot / spring-boot-configurationproperties-example /

这篇关于配置中的属性占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆