java - 如何使用 Spring 创建配置类并在整个代码中共享数据?

标签 java spring spring-boot

我需要创建像共享类这样的东西,我可以通过以下方式使用它:

Shared.getProperty(key);

我尝试使用环境对象,但它始终为空。应该在哪里指定以及如何指定? 我使用 .xml 作为我的 bean 配置。 我还有 application.properties,我想从中检索数据。

最佳答案

// Shared.java
@Component
@ConfigurationProperties("prefix.for.application.properties")
public class Shared {
    private String str;

    // getters, setters
}

// application.properties
prefix.for.application.properties.str=STR

// other code
@Autovired
private Shared shared;

shared.getStr(); 

关于java - 如何使用 Spring 创建配置类并在整个代码中共享数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54389739/

相关文章:

java - 线程 "main"java.lang.RuntimeException : Stub 中的异常

java - 是否可以从 JSTL forEach 循环中的列表访问特定元素/对象?

java - 依赖 jar 中的 Spring Lazy Init = true

spring - 在 Spock 规范中注入(inject)时,WebApplicationContext 不会 Autowiring

java - Android Studio 如何在屏幕上打印可变内容(数字)

java - 在 Solr 中的单个字段上启用小写搜索和 docValues

java - 获取两个变量的百分比

java - 使用 spring 框架时,出现错误 - import org not found

spring - WebFlux 功能 : How to detect an empty Flux and return 404?

java - 如何从拦截器在 Spring 3.1 MVC Controller 上设置对象?