SpringBoot starter,大家应该在平常写项目中应该非常熟悉,很多依赖都会提供集成SpringBoot的依赖,这样我们用起来就非常顺手,开箱就能用,那如何自定义一个starter呢?
SpringBoot中的一大优势就是starter,SpringBoot也提供了很多开箱即用的starter依赖,使得我们开发变更加方便和简单,遵循约定大于配置的理念。
在平常的开发过程中,我们常常会有一些模块是可以独立于业务之外的模块,我们需要把其放到一个特定的包,再通过maven引入,再对其进行配置集成到项目中,比较麻烦。但是我们可以将其封装成一个starter,这样在其他业务中,SpringBoot会将其自动装配到IOC容器中,真香!!!。
我这里就随便集成一个简单的demo
4.0.0 spring-boot-starter-parent org.springframework.boot 2.7.8 cn.zly learn-spring-boot-starter 1.0.0 8 8 org.springframework.boot spring-boot-configuration-processor true org.springframework.boot spring-boot-starter
public class PasswordServiceImpl implements PasswordService {@Overridepublic String encode(String val) {if (val == null) {return null;}byte[] bytes = Base64.getEncoder().encode(val.getBytes());return new String(bytes);}@Overridepublic String decode(String val) {if (val == null) {return null;}byte[] decode = Base64.getDecoder().decode(val.getBytes());return new String(decode);}
}
@Configuration
@ConditionalOnClass(value = {PasswordService.class, PasswordServiceImpl.class})
public class PasswordAutoConfigure {@BeanPasswordService passwordService() {return new PasswordServiceImpl();}
}
org.springframework.boot.autoconfigure.EnableAutoConfiguration=cn.zly.springboot.config.PasswordAutoConfigure
mvn clean install -Dmaven.test.skip=true
在需要使用该项目的pom.xml添加上面的项目三坐标
cn.zly learn-spring-boot-starter 1.0.0
进行测试,我这里是 提前建好了一个项目,并直接在测试类这里进行测试好了,结果肯定也是成功加载到IOC容器了。
@SpringBootTest(classes = HelloWorldApplication.class)
@RunWith(SpringRunner.class)
public class StudentMapperTest {@Autowiredprivate PasswordService passwordService;@Testpublic void testPassword() {String password = passwordService.encode("zly");System.out.println(password);System.out.println(passwordService.decode(password));}
}
到这里,自定义一个SpringBoot starter就成功了,如果觉得对你有帮助,就给个小赞吧👍👍👍
上一篇:大数据技术之Canal入门篇
下一篇:3D立体视觉成像原理介绍【一 】