我知道這是真的老了,但我想我萬一別人折騰這有相同的坎坷經歷我也努力使這項工作。我最終利用了Spring的兩個特性:在上下文啓動後動態註冊bean的能力以及RequestMappingHandlerMapping
對象上的afterPropertiesSet()
方法。
當初始化RequestMappingHandlerMapping
時,它會掃描上下文並創建它需要服務的所有@RequestMapping
的映射(推測可能是出於性能原因)。如果您動態註冊使用@Controller
註釋的bean,它們將不會被選中。要重新掃描此掃描,只需在添加完豆後調用afterPropertiesSet()
即可。
在我的具體使用情況下,我實例化的新@Controller
對象在一個單獨的Spring上下文和它們連接到我的WebMvc方面需要。如何對象沒有爲這雖然事情的細節,所有你需要的是一個對象的引用:
//register all @Controller beans from separateContext into webappContext
separateContext.getBeansWithAnnotation(Controller.class)
.forEach((k, v) -> webappContext.getBeanFactory().registerSingleton(k, v));
//find all RequestMappingHandlerMappings in webappContext and refresh them
webappContext.getBeansOfType(RequestMappingHandlerMapping.class)
.forEach((k, v) -> v.afterPropertiesSet());
例如,你也可以這樣做:
//class annotated with @Controller
MyController controller = new MyController
//register new controller object
webappContext.getBeanFactory().registerSingleton("myController", controller);
//find all RequestMappingHandlerMappings in webappContext and refresh them
webappContext.getBeansOfType(RequestMappingHandlerMapping.class)
.forEach((k, v) -> v.afterPropertiesSet());
感謝斯卡夫,你總要給偉大的祕訣。無論如何,我如何通過代碼操作上下文,我的意思是,是否有一種方法來動態添加HandlerMapping bean或其他bean? – gotch4 2011-04-23 09:01:17
@ gotch4:你不需要動態添加一個'HandlerMapping'。你配置一個*自定義的'HandlerMapping',然後動態地添加映射到它。既然你自己寫了'HandlerMapping',那麼這個工作是由你自己決定的。 – skaffman 2011-04-23 09:12:53