命名归约:
官方命名:
自定义命名:
在IDEA中新建一个空项目 spring-boot-starter-diy
新建一个普通Maven模块:demo-spring-boot-starter
新建一个Springboot模块:demo-spring-boot-starter-autoconfigure
点击apply即可,基本结构
在starter 中 导入 autoconfigure 的依赖
com.demo demo-spring-boot-starter-autoconfigure 0.0.1-SNAPSHOT
将 autoconfigure 项目下,Pom中加入依赖
org.springframework.boot spring-boot-configuration-processor true org.springframework.boot spring-boot-autoconfigure
说明:
第一个依赖 主要是为编译器配置的 可以根据properties 鼠标右键 点到用这个属性的类上个
第二个依赖 主要是为了自动装配
编写HelloProperties 配置类
// 前缀 demo.hello
@ConfigurationProperties(prefix = "demo.hello")
public class HelloProperties {private String prefix;private String suffix;public String getPrefix() {return prefix;}public void setPrefix(String prefix) {this.prefix = prefix;}public String getSuffix() {return suffix;}public void setSuffix(String suffix) {this.suffix = suffix;}
}
这里我们要读取的配置就是demo.hello.prefix 和 demo.hello.suffix 的值
@ConfigurationProperties注解的作用就是读取配置文件指定属性的值
编写一个自己的服务
public class HelloService {HelloProperties helloProperties;public HelloProperties getHelloProperties() {return helloProperties;}public void setHelloProperties(HelloProperties helloProperties) {this.helloProperties = helloProperties;}public String sayHello(String name){return helloProperties.getPrefix() + name + helloProperties.getSuffix();}
}
编写自动配置类并注入bean,测试
@Configuration
@ConditionalOnWebApplication //web应用生效
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfiguration {@AutowiredHelloProperties helloProperties;@Beanpublic HelloService helloService(){HelloService service = new HelloService();service.setHelloProperties(helloProperties);return service;}
}
说明:
@Configuration
标识本类是配置类(相当于spring中application.xml)
@EnableConfigurationProperties(HelloProperties.class)
如果 HelloProperties
中有注解@ConfigurationProperties
那么这个类就
会被加到spring上下文的容器中,也就是可以通过@Autowire来注入
@ConditionalOnClass
当类路径下有指定类的情况下 才进行下一步
@ConditionalOnMissingBean
当spring容器中没有这个Bean的时候才进行下一步
在resources编写一个自己的 META-INF\spring.factories
```java
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.demo.config.HelloServiceAutoConfiguration```
编写完成后,可以安装到maven仓库中
项目包结构
新建一个SpringBoot 项目(需要引入 web 的启动器)
导入我们自己写的启动器
com.demo demo-spring-boot-starter 1.0-SNAPSHOT
编写一个 HelloController 进行测试我们自己的写的接口
@RestController
public class HelloController {@AutowiredHelloService helloService;@RequestMapping("/hello")public String hello(){return helloService.sayHello("zxc");}}
编写配置文件 application.properties
demo.hello.prefix="Mystarter-perfix--"
demo.hello.suffix="--Mystarter-suffix"
启动项目进行测试,结果成功
上一篇:图文素材生成视频TTV——简介