第一个springboot-starter

发布时间 2023-07-17 08:49:38作者: 三丝柚

在一个SpringBoot项目启动时会默认扫描当前启动类SpringApplication所在目录的所有子目录,并扫描引入的jar的spring.factories文件,通过此文件把相关的配置加载到spring的容器中。

编辑自己的starter

方式1:通过META-INF/spring.factories文件进行加载

  • springboot启动会扫描spring.factories 文件,在文件中写入以下内容
    org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.s.q.g.config.SqgAutoConfig

  • 创建相关类,通过类名上@Configuration和方法上的@Bean 创建一个bean。

/**
 * @description: 通过spring.factories 文件指定当前类,进行加载到spring。
 **/
@Configuration
public class SqgAutoConfig {
    @Bean
    StorageService StorageService() {
        logger.debug("执行了构造方法");
        logger.info("执行了构造方法");
        return new StorageService(properties);
    }
}
  • 在另外的SpringBoot项目中通过maven的方式引入该starter,启动即可把此Bean加载的spring中。

方式2:通过@Import注解进行加载

  • 编辑一个自定义注解@EnableStorage

/**
 * @description: 通过@Import注解进行导入,把bean加载到spring。
 **/

@Configuration
public class SqgAutoConfig {
    @Bean
    StorageService StorageService() {
        logger.debug("执行了构造方法");
        logger.info("执行了构造方法");
        return new StorageService(properties);
    }
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(SqgAutoConfig.class)//启动是加载的类
@Documented
public @interface EnableStorage { } 
  • 在另外的项目中通过maven引入,并且在启动类上使用注解@EnableStorage。
@SpringBootApplication
@EnableStorage
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}