-
引入相应的jar包
<!-- API获取的包 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <!-- 官方UI包 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <!-- 测试数据以JSON格式返回的依赖包 --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.13</version> </dependency>
-
写一个swagger的配置类
@Configuration @EnableSwagger2 @Profile({"dev", "sit"}) public class SwaggerConfig { @Bean public Docket createRestApi() { System.out.println("swagger config 生效了"); return new Docket(DocumentationType.SWAGGER_2) .pathMapping("/") .select() .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .paths(PathSelectors.any()) .build().apiInfo(new ApiInfoBuilder() .title("SpringBoot整合Swagger") .description("SpringBoot整合Swagger,详细信息......") .version("1.0") // .license("The Apache2.0") // .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0") .build()); } }
-
编写对应的Controller
@Api(tags = "test") @RestController @RequestMapping("/test") public class TestController { @Autowired private TestService testService; @ApiOperation("测试运行") @GetMapping("/demo") public String test() { return "hello world"; } @ApiOperation("测试运行2") @GetMapping("/demo2") public String test2(String name) { return name + "hello world"; } @ApiOperation("测试dubbo使用") @GetMapping("/dubbo") public String dubbo() { return testService.testDemo(); } }
-
如果真正的项目编写还需要将swagger的地址设置成无须安全校验即可访问。
父工程配置类
- 父工程配置类之所以能够生效是因为目录结构与子工程相同,因此在执行ComponentScan时会识别到启动类同目录下或其子类下的配置类。
组件jar包引入使用解决方案
-
友好度从高到低排序
-
springboot 主动发现,配置一个resources/META-INF/spring.factories 文件,boot中有程序会读取该文件执行自动配置。
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.baoyong.base.demo.BaseDemoConfig
org.springframework.boot.autoconfigure.EnableAutoConfiguration 代表自动配置的 key, 即代表需要自动配置哪些类;
\ 可以理解为一个换行符,则该行下面的每行当做一个参数;
第二行则为配置类的全路径,如果需要 Spring 自动配置多个类,依行写入它的全路径即可
-
使用者通过注解方式启用配置:
-
生产者工程创建一个统一的组件入口配置类,创建配置文件读取目录下的配置类。
@Configuration @ComponentScan("com.baoyong.base.demo.**"}) public class BaseDemoConfig{ }
-
生产者工程创建一个注解提供给用户使用,因此需要创建一个注解:
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Documented // 该注解引入了前面编写的配置类,让该类正常生效 @Import({BaseDemoConfig.class}) public @interface EnableBaseDemo { }
-
用户使用如下,当启动程序时,前面的BaseDemoConfig就会被注册到bean,其本身的ComponentScan也会正常生效。
@EnableLogRecordClient @Configuration public class ConsumerConfig { }
-
-
使用者手动配置basePackages,这要求使用者熟悉知道配置文件路径;自创建项目根路径一般相同,无须配置也可以正常使用。
@Configuration @ComponentScan(basePackages = {"com.baoyong.base.demo.**"}) public class ConsumerConfig{ }
-
-
根据情况使用方案1或2,目前最适合springboot的个人认为是方式1,用户可以无须配置直接引入使用。