java - 配置中的属性占位符

标签 java spring

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

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

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

谢谢!

最佳答案

你可以像这样使用注解@PropertySource

@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

编辑:如果您使用的是 spring boot,则可以使用 @ConfigurationProperties 注释将属性文件直接连接到 bean 属性,如下所示:

测试.properties

name=John Doe
age=12

PersonProperties.java

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

    private int age;
    private String name;

    //getters and setters
}

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

关于java - 配置中的属性占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14724512/

相关文章:

java - Java 类的消息正文编写器...和 ​​MIME 媒体类型文本/html 未找到

java - 将 ".00"添加到 Java 中的整数 BigDecimal

spring - 使用resttemplate从xml解码对象时出现错误

java - Spring RestController POST 400 错误请求

java - 打印 ArrayList Integer 的值

java - 是否可以设计 java 应用程序的样式?

java - 检测接触的多边形

java - Spring Config 将字符串映射到对象

java spring框架知识巩固

java - 如何停止在 Spring-JDBC 中处理行?