5.springboot原理深入了解
自定义Starter:
-
新建一个空项目
-
在该项目中添加一个普通的maven模块
-
再改项目中的依赖中添加:
<dependency> <groupId>com.ariverh</groupId> <artifactId>ariverh-spring-boot-starter-autoconfigure</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <version>2.4.0</version> </dependency>
-
再添加一个springboot模块
-
再pom中只留下
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency>
-
建立一下目录结构
-
编写各类:
public class Hello { private HelloProperties helloProperties; public HelloProperties getHelloProperties() { return helloProperties; } public void setHelloProperties(HelloProperties helloProperties) { this.helloProperties = helloProperties; } public String getHello(){ return helloProperties.getPrefix()+"-hello-"+helloProperties.getSuffix(); } }
@ConfigurationProperties(prefix = "ariverh.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; } }
@Configuration @ConditionalOnWebApplication @EnableConfigurationProperties(HelloProperties.class) public class HelloAutoConfiguration { @Autowired HelloProperties helloProperties; @Bean public Hello hello(){ Hello hello = new Hello(); hello.setHelloProperties(helloProperties); return hello; } }
# Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.ariverh.mystarter.HelloAutoConfiguration
-
打包这两个模块
-
新建一个springboot项目
-
导入启动器
<dependency> <groupId>com.ariverh</groupId> <artifactId>ariverh-spring-boot-starter</artifactId> <version>1.0-SNAPSHOT</version> </dependency>
-
编写测试
@RestController
@RequestMapping("/ariverh")
public class HelloController {
@Autowired
Hello hello;
@RequestMapping("/hello")
public String hello(){
String hello = this.hello.getHello();
return hello;
}
}
-
在application.properties中编写配置
ariverh.hello.prefix=yyy ariverh.hello.suffix=sss
-
测试