Spring Boot中的插件系统用于模块化应用程序

时间:2014-09-09 19:13:57

标签: spring spring-mvc spring-boot

我正在寻找在编译后在spring boot中动态加载jar,例如我将jar放在某个文件夹中,当spring boot启动时,此文件夹中的所有jar都会被注入spring boot app。我不知道怎么能用春季靴子做到这一点,如果你知道可以帮我这个,举个例子。

我需要这个罐子有@Service,@ Controller,因为这将是模块(插件),并为我的春季启动应用程序添加功能。

可以使用弹簧启动执行此操作,如果可以,请提供一些示例代码。

提前致谢。

更新: 我找到了https://www.youtube.com/watch?v=F-sw2pFdcDw https://code.google.com/p/jspf/

的内容

更新2:我无法从Spring Boot中注册的插件jar获取@Controller bean

3 个答案:

答案 0 :(得分:1)

一种选择绝对是使用广泛的@ComponentScan。如果您将新jar添加到classpath,那么该jar中带注释的类将通过@ComponentScan被发现,@Controller将被映射等。

这里的XML等价物将xml配置文件放在您的类路径(META-INF文件夹显而易见的选择)的某处,并使用通配符将它们全部导入。这个想法是一样的。如果插件jar文件在classpath上,您将获得导入的xml文件,并且bean(控制器,......)将被加载。

这种方法有一些缺点,例如模块不是孤立的,但它是更简单应用的绝对选择。

答案 1 :(得分:1)

看看 FlexiCore,这是一个开源框架,它利用在运行时加载的插件(jar)为 Spring Boot 带来模块化。请参阅 wizzdi 和 FlexiCore。 例如,FlexiCore 允许您创建一个包含 spring bean 的项目(从主应用程序编译成一个单独的 jar),如下所示:

@Component
@Extension
public class HelloWorldService implements ServicePlugin{

 public String hello() {
  return "Hello World!";
 }

}

一旦放置在指定的插件文件夹中,它将自动加载,它基本上允许对大多数(所有)spring boot 功能的完全支持,因此例如您也可以将 RestController bean 添加到您的 jar 中,FlexiCore 将自动加载该 bean,允许您像在主应用程序 jar 中一样调用控制器:

@RestController
@Extension
public class TestEntityController implements Plugin {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @Autowired
    private TestEntityService testEntityService;

    @PostMapping("/createTestEntity")
    public TestEntity createTestEntity(@RequestParam(name="name", required=false, defaultValue="Stranger") String name) {
        return testEntityService.createTestEntity(name);
    }

    @GetMapping("{id}")
    public TestEntity getTestEntity(@PathVariable("id")String id) {
        return testEntityService.getTestEntity(id);
    }

}

免责声明:我是 wizzdi 的首席技术官,该公司为 FlexiCore 提供支持。

答案 2 :(得分:0)

您可以找到示例弹出启动Web项目here

通过动态加载jar我假设您要为项目添加依赖项。为此,您可以更新示例项目的pom.xml并将依赖项放在此处。