1. Let's start with a question: What if the path of the Bean managed by the Spring container is no longer under Spring Book's packet scanning path? How do I load third-party beans?
There are two ways to solve this problem:
Here we use Swagger configuration to do the experiment.
1: First of all, a Swagger configuration class: SwaggerConfig
SwaggerConfig code:
@Configuration @EnableSwagger2 public class SwaggerConfig implements EnvironmentAware { private static final Logger log = LoggerFactory.getLogger(SwaggerConfig.class); @Autowired private Environment env; @Value("${swagger.scan.package}") private String swaggerScanPackage; public SwaggerConfig() { } @Bean public Docket createRestApi() { Predicate<String> path = PathSelectors.any(); if (Arrays.asList(this.env.getActiveProfiles()).contains("prod")) { path = PathSelectors.none(); } log.info("####Initialization createRestApi####swaggerScanPackage:" + this.swaggerScanPackage); log.info(path.toString()); return (new Docket(DocumentationType.SWAGGER_2)).apiInfo(this.apiInfo()).select().apis(RequestHandlerSelectors.basePackage(this.swaggerScanPackage)).paths(PathSelectors.any()).build(); } private ApiInfo apiInfo() { log.info("##################################Initialization API information################################################"); return (new ApiInfoBuilder()).title("APIs").description("............").termsOfServiceUrl("https://js.dazhi.loan.com").version("1.0").build(); } @Override public void setEnvironment(Environment environment) { } }
2: Look at my engineering structure again.
It was found that my SwaggerConfig class and SpringBoot startup class ConfigApplication.java were not in the same level directory, so when SpringBoot automatically scanned the package, it could not scan my SwaggerConfig configuration, so there was no Swagger print information in the console:
So what if I want to load SwaggerConfig into the Spring container at this time? Here are two ways
(1) Use the @Import annotation on the Spring Boot Application main class
You can see Swagger's basic information at startup:
(2) Now let's transform it, load SwaggerConfig class by spring.factories, create a new META-INF directory under resources directory, and then
Create a new spring.factories file with the following contents:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.sg.config.SwaggerConfig
Then annotate @Import on the Spring Boot boot class, and boot discovery can also load SwaggerConfig into the Spring container.
This completes loading a class that Spring can't scan, it can be a third party, it can also be written by itself, as long as the default scanning path of Spring Boot can not be scanned, you can use this way to load!!!