我的web應用程序以後端服務的默認impl運行。一個應該能夠實現接口並將jar放入plugins文件夾(不在apps classpath中)。一旦服務器重新啓動,想法就是將新的jar加載到類加載器中,並讓它參與依賴注入。我使用@Autowired使用Spring DI。新的插件服務impl將有@Primary註釋。所以給定兩個接口的impls,主要應該加載。Spring依賴注入和插件Jar
我得到的罐子裝入類加載器,可以手動調用implement執行。但我一直無法參與依賴注入,並且已經取代了默認的impl。
這裏有一個簡單的例子:
@Controller
public class MyController {
@Autowired
Service service;
}
//default.jar
@Service
DefaultService implements Service {
public void print() {
System.out.println("printing DefaultService.print()");
}
}
//plugin.jar not in classpath yet
@Service
@Primary
MyNewService implements Service {
public void print() {
System.out.println("printing MyNewService.print()");
}
}
//由於缺乏更好的地方,我從ContextListener
public class PluginContextLoaderListener extends org.springframework.web.context.ContextLoaderListener {
@Override
protected void customizeContext(ServletContext servletContext,
ConfigurableWebApplicationContext wac) {
System.out.println("Init Plugin");
PluginManager pluginManager = PluginManagerFactory.createPluginManager("plugins");
pluginManager.init();
//Prints the MyNewService.print() method
Service service = (Service) pluginManager.getService("service");
service.print();
}
}
<listener>
<listener-class>com.plugin.PluginContextLoaderListener</listener-class>
</listener>
即使我已經加載的水罐裏的類加載器加載的插件jar, DefaultService仍然被注入爲服務。任何想法如何讓插件jar參與到spring的DI生命週期中?
編輯: 簡而言之,我有一個戰爭文件,在戰爭中的插件目錄中有幾個插件罐。根據應用程序查看的配置文件中的值,當應用程序啓動時,我想加載該特定的插件jar並使用它運行應用程序。這樣,我可以將戰爭分發給任何人,並且他們可以根據配置值選擇運行哪個插件,而無需重新打包所有內容。這是我想解決的問題。
謝謝。看起來像會起作用。但是我大量使用Spring Annotations,並且在插件罐中沒有任何spring xml。我想知道做註解驅動的依賴注入的做法與上面相同是多麼容易。 – Langali
您應在每個插件中進行某種配置(請參閱我的擴展回答)。即使只有一個小的xml,只有一個插件包的' ',它應該是插件**中的**,以及其他任何地方。這是插件,知道自己最好的,知道如何配置自己。核心模塊不應該意識到插件的存在 - 它只應該爲他們提供將自己的配置加入到ApplicationContext中的可能性。 –
Roadrunner