现在的项目都是以springboot为脚手架进行开发的主要原因是由于springboot有自动装载的功能,通俗的来讲,就是引入对应starter依赖就可以实现相应的功能,那我们如何实现自定义starter呢
由于项目中都需要登录认证功能,我们可以把登录认证功能抽取,封装成starter,直接引入项目中,就可以实现登录认证功能。
公司公共依赖、响应体,异常等处理,都可以封装成starter创建自定义starter
<?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
public 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;
}
}
@ConfigurationProperties(prefix = "hello")
@Data
public class HelloProperties {
private String name;
private String address;
}
@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());
}
}
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.gz.hellospringbootstarter.config.HelloServiceAutoConfiguration
@RestController
@RequestMapping("/hello")
public class HelloController {
//HelloService在我们自定义的starter中已经完成了自动配置,所以此处可以直接注入
@Autowired
private HelloService helloService;
@GetMapping("/say")
public String sayHello(){
return helloService.sayHello();
}
}
com.gz
hello-spring-boot-starter
1.0-SNAPSHOT
hello
name: guozhong
address: qingdao
页面更新:2024-05-28
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号