![](/img/trans.png)
[英]How to properly load and configure Spring beans from an external utility jar
[英]How to load beans according to Spring java conf from jar dynamically?
我有這樣的應用程序 conf,jar 將在啟動后添加到類路徑中:
@Configuration
@ComponentScan("com.transportexchangegroup.testConf")
public class AppConf {
}
如何動態加載bean? 當需要編寫和添加 bean 定義時,我看到了 Solutionsm,但是如果我們對新 bean 一無所知,只想自動加載它們?
Class conf = jarService.loadClass("com.x.testConf.AppConf");
((AnnotationConfigServletWebServerApplicationContext) applicationContext).register(conf);
((AnnotationConfigServletWebServerApplicationContext) applicationContext).refresh();
如我所見,refresh() 關閉了從 IDE 本地啟動的 Web 應用程序。
您知道任何其他解決方案或有什么問題嗎? 這對 jar 中的彈簧休息控制器有用嗎?
我不確定你是什么意思“動態”。 通常,如果某些條件適用,您可以加載 bean,通常取決於配置。 所以你可以做這樣的事情:
application.properties: // or yaml it doesn't matter
feature.enabled=true
@Component
@ConditionalOnProperty(name="feature.enabled", havingValue="true", matchIfMissing="true" / "false") // matchIfMissing depends on whether you want the bean to be loaded if the property is not defined
public MyBean {
}
一些注意事項:
如果您有許多依賴“業務”功能的 bean 以避免放置@ConditionalOnProperty
您可以執行以下操作之一:
@Component
注解:// runtime retention, place on class
@Component
@ConditionalOnProperty(...)
@MyFeatureComponent
...並在定義該功能的所有 bean 中使用它:
@MyFeatureComponent
public class MyBean
{}
@Configuration
@ConditionalOnProperty(...)
public class MyFeatureConfiguration {
@Bean
public MyBean myBean(){return new MyBean();}
@Bean
public MyAnotherBean myAnotherBean(){return new MyAnotherBean();}
}
在這種情況下,您根本不需要在MyBean
上放置任何注釋。
Spring 也有一個 profile 的概念,它是一樣的,它在底層實現了這些條件。 然而,它允許為每個配置文件定義配置文件,因此您可能還想了解@Profile
注釋。
至於 bean 定義 - 這是更高級的東西,一般來說,當 spring 加載它時,它“識別”應該加載哪個 bean 以及加載順序,為此它在加載 bean 之前創建一個 bean 定義。 因此,如果您進入這個過程,您可以根據需要定義自己的 bean 定義,spring 也會基於這些定義創建 bean。 所以基本上它是一個鈎子,它允許在啟動過程中更改 bean 定義/創建新定義,從而影響將加載到應用程序上下文中的實際 bean。 我對此表示懷疑,但如果您真的需要它,請在春季閱讀 Bean Factory Post Processors。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.