java - Spring MVC - 在 Controller 上设置初始化属性

标签 java spring jakarta-ee spring-mvc properties

我有一个 Spring MVC,它使用我无法访问代码的外部库。这个外部库使用标准的 system.getProperty 调用读取一些属性。我必须在使用该服务之前设置这些值。

由于我的应用程序是一个 Spring MVC 应用程序,我不确定如何初始化这些属性。这是我到目前为止所做的,但由于某种原因,我的值始终为空。

我将属性放在属性文件 /conf/config.properties

my.user=myuser
my.password=mypassowrd
my.connection=(DESCRIPTION=(LOAD_BALANCE=on)(ADDRESS=(PROTOCOL=TCP)(HOST=xxxx.xxxx.xxxx)(PORT=1521))(ADDRESS=(PROTOCOL=TCP)(HOST=xxx.xxx.xxx)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=myService)))

然后我在我的 applicationContext.xml

中添加了以下两行
<context:annotation-config/>
<context:property-placeholder location="classpath*:conf/config.properties"/>    

我阅读了有关设置初始化代码的文档,您可以实现 InitializingBean 接口(interface),因此我实现了该接口(interface)并实现了 afterPropertiesSet() 方法。

private static @Value("${my.user}") String username;
private static @Value("${my.password}") String password;
private static @Value("${my.connection}") String connectionString;  

@Override
    public void afterPropertiesSet() throws Exception {     
        System.setProperty("username",username);
        System.setProperty("password",password);
        System.setProperty("connectionString",connectionString);
    } 

问题是调用 afterPropertiesSet() 方法时,值始终为 null。

  • 上述方法是否是初始化代码(尤其是 Controller )的正确方法?如果对 Controller 进行第二次调用会怎样?
  • 由于初始化,这些值是否为空?即 spring 还没有设置它们?
  • 是否可以在 Controller 之外添加初始化代码?

最佳答案

您确定您的 bean/ Controller 的定义与您拥有 property-placeholder 定义的位置在同一个 spring 上下文配置文件中吗?

看看鲍里斯对这个问题的回答:Spring @Value annotation in @Controller class not evaluating to value inside properties file

如果你想从你的 Controller 中移动你的代码,你可以添加一个组件来监听 spring 何时完成初始化,然后调用代码:

@Component
public class ApplicationStartedListener implements ApplicationListener<ContextRefreshedEvent> {

    private static @Value("${my.user}") String username;
    private static @Value("${my.password}") String password;
    private static @Value("${my.connection}") String connectionString;

    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.setProperty("username",username);
        System.setProperty("password",password);
        System.setProperty("connectionString",connectionString);
    } 
}

关于java - Spring MVC - 在 Controller 上设置初始化属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14112076/

相关文章:

java - jackson 解析复杂对象

java - 无法将 Spring HATEOAS 集成到我现有的 Spring Boot REST API 中

java - 重复类定义错误

java - 字符串解析: how to isolate parameters when a parameter can be a nested function

java - SQLException : Operation not allowed after ResultSet closed error

java - 了解 Spark 异步操作

java - 在业务层返回业务验证结果的首选方法是什么

Spring JPA 存储库查找所有不存在的内容

java - Spring方法替换final方法

jakarta-ee - 缺少 [类(class)] 的类(class)详细信息。为 [class] 使用现有的类字节