- 创建springboot starter
- 创建一个demo starter
-
创建配置类
@Configuration @EnableConfigurationProperties(EmailProperties.class) @ConditionalOnBean(EmailEnable.class) public class EmailAutoConfiguration { static { System.out.println("EmailAutoConfiguration init..."); } @Bean public EmailServiceImpl emailServiceImpl() { return new EmailServiceImpl(); } } // ============================================= public class EmailEnable { } // ============================================= @ConfigurationProperties(prefix = "email.config") public class EmailProperties { } // ============================================= @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Import(EmailEnable.class) public @interface EnableAutoEmail { }
- 创建具体业务类型
public interface EmailService { void sendEmail() throws EmailServiceException; } //======================================== public class EmailServiceImpl implements EmailService { @Override public void sendEmail() throws EmailServiceException { } }
- 增加配置文件 resource目录下创建一个META-INF文件夹,这里需要注意的是EmailAutoConfiguration需要放到一个根目录下。
org.springframework.boot.autoconfigure.EnableAutoConfiguration=XXX.EmailAutoConfiguration
- 将项目install到本地的maven库中,打包时需要注意一下,SpringBoot项目打包的JAR是可执行JAR,它的类放在BOOT-INF目录下,如果直接作为其他项目的依赖,会找不到类。可以通过修改pom文件来解决,代码如下:
<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <classifier>exec</classifier> </configuration> </plugin>
如果需要上传私有maven中,需要配置以下代码:
<distributionManagement> <repository> <id>XXX</id> <name>XXX</name> <url>XXX</url> <layout>default</layout> </repository> <snapshotRepository> <id>XXX</id> <name>XXX</name> <url>XXX</url> </snapshotRepository> </distributionManagement>
- 使用springboot start,引入包
<dependency> <groupId>com.example</groupId> <artifactId>demo2</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
- 开启starter,需要在ApsUiApplicationServer中增加@EnableAutoEmail 注解
- 测试
public class MailTest extends ApplicationTest { @Autowired private EmailService emailService; @Test public void sendEmail2() throws EmailServiceException { emailService.sendEmail(); } }