Skip to content

spring-boot模拟引用第三方库中包含RestController

例子详细请参考 链接

例子中包括demo-third-party-libdemo-tester两个子项目,其中demo-third-party-lib用于模拟第三方依赖库,demo-tester用于测试引入demo-third-party-lib第三方依赖库。demo-third-party-lib中的MyXxxController定义了/api/v1/test1接口并通过EnableXxxThirdParty注解暴露给调用者应用。

运行例子的步骤:

  1. 编译并安装demo-third-party-lib到本地maven

    bash
    mvn package install
  2. 使用IntelliJ IDEA运行demo-tester的测试用例

创建MyXxxController并定义/api/v1/test1接口

java
// 此Controller用于当作第三方库被动态引用测试
@RestController
@RequestMapping("/api/v1")
public class MyXxxController {
    @GetMapping("test1")
    ObjectResponse<String> test1() {
        return ResponseUtils.successObject("Hello world!");
    }
}

MyThirdPartyConfiguration手动创建MyXxxController实例以注册/api/v1/test1接口到spring容器中

java
public class MyThirdPartyConfiguration {
    // 手动创建Controller并注入到spring容器中,否则在引用这个库的应用中不能自动扫描并实例化相关Controller
    @Bean
    MyXxxController myXxxController() {
        return new MyXxxController();
    }
}

外部应用通过注解@EnableXxxThirdParty注册/api/v1/test1接口到spring容器中

java
// 调用这个注解启用此库
@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = {java.lang.annotation.ElementType.TYPE})
@Documented
@Import({MyThirdPartyConfiguration.class})
public @interface EnableXxxThirdParty {

}

demo-tester中引用demo-third-party-lib依赖

xml
<dependency>
    <groupId>com.future.demo</groupId>
    <artifactId>demo-third-party-lib</artifactId>
    <version>1.0.0</version>
</dependency>

demo-tester中启用demo-third-party-lib注册/api/v1/test1接口

java
@SpringBootApplication
// 启用第三方库(实例化相关controller并注入到spring容器中)
@EnableXxxThirdParty
public class Application {
    public static void main(String []args){
        SpringApplication.run(Application.class, args);
    }
}