springboot自定义starter实战

自定义starter

思路

将我们的bean,加载到调用者的spring容器中。
还是采用@configuration和@bean,或是@component注解。

@component

如果采用这种方式,需要在调用的主类上添加扫描到starter的路径,@ComponentScan("#{start的包路径}","#{自己项目的路径}")

@Configuration

方式一

1、实现ImportSelector接口,将所有的@Configuration定义

import com.example.Application;
import com.example.hello.HelloServiceAutoConfiguration;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;

public class MyImportor implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        return new String[]{
                Application.class.getName(),
                HelloServiceAutoConfiguration.class.getName()
        };

    }
}

2、定义一个组合注解,组合Import

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Import(MyImportor.class)
public @interface EnableSDK {
}
方式二

spring.factories中编写,无侵入
\代表换行

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.example.hello.HelloServiceAutoConfiguration,\
  com.example.log.MyLogAutoConfiguration

git

https://github.com/lexiaoyao1995/customerStarter

posted @ 2020-11-10 19:24  刃牙  阅读(225)  评论(0编辑  收藏  举报