2009-02-10 254 views

回答

7

我不会推荐你这样做。 你期望发生的单身豆,他们的配置修改了什么?你期望所有的单身人士重新加载吗?但有些对象可能会持有对该单例的引用。

看到这个职位以及Automatic configuration reinitialization in Spring

10

嗯,这可能是在测试你的应用程序来执行这样一个背景下重装有用。

您可以尝试AbstractRefreshableApplicationContext类之一的refresh方法:它不会刷新先前实例化的bean,但下一次调用上下文时将返回刷新的bean。

import java.io.File; 
import java.io.IOException; 

import org.apache.commons.io.FileUtils; 
import org.springframework.context.support.FileSystemXmlApplicationContext; 

public class ReloadSpringContext { 

    final static String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + 
     "<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN//EN\"\n" + 
     " \t\"http://www.springframework.org/dtd/spring-beans.dtd\">\n"; 

    final static String contextA = 
     "<beans><bean id=\"test\" class=\"java.lang.String\">\n" + 
      "\t\t<constructor-arg value=\"fromContextA\"/>\n" + 
     "</bean></beans>"; 

    final static String contextB = 
     "<beans><bean id=\"test\" class=\"java.lang.String\">\n" + 
      "\t\t<constructor-arg value=\"fromContextB\"/>\n" + 
     "</bean></beans>"; 

    public static void main(String[] args) throws IOException { 
     //create a single context file 
     final File contextFile = File.createTempFile("testSpringContext", ".xml"); 

     //write the first context into it 
     FileUtils.writeStringToFile(contextFile, header + contextA); 

     //create a spring context 
     FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(
      new String[]{contextFile.getPath()} 
     ); 

     //echo the bean 'test' on stdout 
     System.out.println(context.getBean("test")); 

     //write the second context into it 
     FileUtils.writeStringToFile(contextFile, header + contextB); 

     //refresh the context 
     context.refresh(); 

     //echo the bean 'test' on stdout 
     System.out.println(context.getBean("test")); 
    } 

} 

,你会得到这样的结果

fromContextA 
fromContextB 

另一种方式来实现这一目标(也许更简单的一个)是使用Spring 2.5+ 随着动态语言的可刷新豆功能(常规,等等)和春天,你甚至可以改变你的bean行为。看看spring reference for dynamic language

24.3.1.2。刷新豆

之一(如果不是)Spring对动态 语言支持中最引人注目的 价值在于增加了对 “刷新豆”功能。

可刷新的豆是 动态语言支持的豆与 少量配置,一个 动态语言支持的bean可以 监视器改变它的底层 源文件资源,然后重新装入 本身当动态语言 源文件发生更改(例如, ,当开发人员编辑并保存 文件系统上的文件时,更改为 )。

2

你可以看看这个http://www.wuenschenswert.net/wunschdenken/archives/138,一旦你改变了属性文件中的任何东西并保存它,bean就会重新载入新的值。

+0

这是在https://github.com/Unicon/springframework-addons/wiki/Auto-reloading-properties-files – Vadzim 2014-08-29 16:16:46

1

对于那些最近遇到的问题 - 目前和现代的解决方法是使用Spring Boot's Cloud Config

只需在您的可刷新豆上添加@RefreshScope注释,并在您的主/配置上添加@EnableConfigServer

因此,举例来说,该控制器类:

@RefreshScope 
@RestController 
class MessageRestController { 

    @Value("${message}") 
    private String message; 

    @RequestMapping("/message") 
    String getMessage() { 
     return this.message; 
    } 
} 

会回到你的message String属性的新价值,为/message终点时,您的配置更新。

中查看实施细则正式Spring Guide for Centralized Configuration例子。

相关问题