springboot自定义starter
序言
现在的项目都是以springboot为脚手架进行开发的主要原因是由于springboot有自动装载的功能,通俗的来讲,就是引入对应starter依赖就可以实现相应的功能,那我们如何实现自定义starter呢应用场景登录认证功能
由于项目中都需要登录认证功能,我们可以把登录认证功能抽取,封装成starter,直接引入项目中,就可以实现登录认证功能。公司基础框架
公司公共依赖、响应体,异常等处理,都可以封装成starter创建自定义starter
1创建自定义starter1.1配置pom.xml<?xml version="1.0" encoding="UTF-8"?> 4.0.0 org.springframework.boot spring-boot-starter-parent 2.7.4 com.gz hello-spring-boot-starter 1.0-SNAPSHOT hello-spring-boot-starter hello-spring-boot-starter 1.8 org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-configuration-processor true org.springframework.boot spring-boot-starter-web org.projectlombok lombok org.springframework.boot spring-boot-autoconfigure 1.2创建servicepublic class HelloService { private String name; private String address; public HelloService(String name, String address) { this.name = name; this.address = address; } public String sayHello(){ return "你好!我的名字叫 " + name + ",我来自 " + address; } } 1.3创建配置类属性@ConfigurationProperties(prefix = "hello") @Data public class HelloProperties { private String name; private String address; } 1.4创建配置类@Configuration @EnableConfigurationProperties(HelloProperties.class) public class HelloServiceAutoConfiguration { private HelloProperties helloProperties; //通过构造方法注入配置属性对象HelloProperties public HelloServiceAutoConfiguration(HelloProperties helloProperties) { this.helloProperties = helloProperties; } //实例化HelloService并载入Spring IoC容器 @Bean @ConditionalOnMissingBean public HelloService helloService(){ return new HelloService(helloProperties.getName(),helloProperties.getAddress()); } } 1.5创建META-INF/spring.factoriesorg.springframework.boot.autoconfigure.EnableAutoConfiguration= com.gz.hellospringbootstarter.config.HelloServiceAutoConfiguration 2.创建测试项目2.1创建controller@RestController @RequestMapping("/hello") public class HelloController { //HelloService在我们自定义的starter中已经完成了自动配置,所以此处可以直接注入 @Autowired private HelloService helloService; @GetMapping("/say") public String sayHello(){ return helloService.sayHello(); } } 2.2引入pom.xml com.gz hello-spring-boot-starter 1.0-SNAPSHOT 2.3 application.ymlhello name: guozhong address: qingdao2.4访问