方式一:Spring SPI

META-INF\spring.factories

  1. org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  2. com.example.boot.serve.starter.AppConfig

方式二:

利用 @Import 注解,导入一个实现了 ImportSelector 接口的类,然后由这个类,完成 Configuration 的注册

  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Import(SwitchLoggerImport.class)
  4. public @interface EnableSwitchLogger {
  5. }
  6. public class SwitchLoggerImport implements ImportSelector {
  7. @Override
  8. public String[] selectImports(AnnotationMetadata annotationMetadata) {
  9. return new String[]{SwitchLoggerConfig.class.getName()};
  10. }
  11. }

自动配置类

  1. @Configuration
  2. @Import({Heartbeat.class})
  3. @ConditionalOnBean({ServeMarker.class})
  4. @EnableConfigurationProperties({ServeProperties.class})
  5. public class AppConfig {
  6. @Bean
  7. public ServeController serveController() {
  8. return new ServeController();
  9. }
  10. @Bean
  11. public ServletRegistrationBean<Servlet> servletRegistrationBean() {
  12. ServletRegistrationBean<Servlet> registrationBean = new ServletRegistrationBean();
  13. registrationBean.setServlet(new DispatcherRegisterServlet());
  14. registrationBean.addUrlMappings(new String[]{"*.do"});
  15. registrationBean.setLoadOnStartup(1);
  16. return registrationBean;
  17. }
  18. }