java - Spring 如何在运行时从 application.properties 重新加载值

标签 java spring spring-mvc dependency-injection

在我的 Spring 应用程序中,我从应用程序外部加载 application.properties 文件,例如/user/home/properties/application.properties。文件中的值通过 bean 中的 @Value 注释注入(inject)。我的新要求是能够更改 application.properties 文件中的值并重新加载(或重新注入(inject))bean 中的新值。

在 Spring 3.2 中可以实现这样的功能吗?

最佳答案

在主类中的独立 spring 应用程序中,您可以执行如下操作:

 //load the appcontext with refresh value as false
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                    new String[] { "classpath:appcontext.xml" }, false);
//add the props file
context.getEnvironment().getPropertySources().addFirst(new ResourcePropertySource("classpath:app.properties"));
//refresh the context
context.refresh();

这样做是用在 appcontext.xml 文件中调用的所有属性中定义的属性加载 spring 上下文,但不会在加载时刷新。然后它说首先加载 app.properties。那时只考虑 app.properties 中的值。然后上下文被刷新。现在加载了 app.properties 文件中的属性值。有了这个,您不需要重建应用程序,您只需更改值并重新启动应用程序即可

关于java - Spring 如何在运行时从 application.properties 重新加载值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15274547/

相关文章:

java - Android OCR(光学字符识别)

java - JAX-RS 服务抛出 404 HTTPException 但客户端收到 HTTP 500 代码

java - Spring appConfig.java 类如何工作

java - 在同一台机器上同时运行 ActiveMQ 和 RabbitMQ 时 AMQP 协议(protocol)版本不匹配

java - Spring MVC - 如何在jsp页面上显示CSV文件中的每一行数据?

java - 如何在 Spring 中发送和检索参数?

java - 是否可以同时使用 TextStyle.SHORT 和 TextStyle.FULL 解析当月的日期?

java - 我正在使用 volley 进行登录 api,但出现 ssl 握手错误

spring - orm.CompilationManager 问题 : java compilation Error in Spring

java - OpenEntityManagerInViewFilter批注配置