相关疑难解决方法(0)

Spring依赖注入和插件Jar

我的Web应用程序运行时带有后端服务的默认impl.一个人应该能够实现接口并将jar放入plugins文件夹(不在apps类路径中).重新启动服务器后,我们的想法是将新jar加载到类加载器中,并让它参与依赖注入.我使用@Autowired使用Spring DI.新的插件服务impl将具有@Primary注释.因此,给定两个接口的impls,应该加载primary.

我将jar加载到类加载器中并可以手动调用impl.但是我无法参与依赖注入,并让它替换默认的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()");
   } 
}
Run Code Online (Sandbox Code Playgroud)

//由于缺少更好的地方,我从ContextListener加载了插件jar

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();                  
            }
    } …
Run Code Online (Sandbox Code Playgroud)

java plugins spring java-ee

13
推荐指数
1
解决办法
3440
查看次数

标签 统计

java ×1

java-ee ×1

plugins ×1

spring ×1