这里模拟一个自动配置的自定义
- 新建空项目,随后在空项目中新建2个springboot模块
- 在
flyyant-hello-spring-boot-starter
中引入flyyant-hello-spring-boot-starter-configure
的依赖
<dependency>
<groupId>com.flyyant</groupId>
<artifactId>flyyant-hello-spring-boot-starter-configure</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
- 清空
flyyant-hello-spring-boot-starter
项目内无用文件 - 清空
flyyant-hello-spring-boot-starter-configure
项目内无用依赖
- 在
flyyant-hello-spring-boot-starter-configure
项目中新建如下文件
- HelloServiceAutoConfiguration.java
@Configuration
@EnableConfigurationProperties(HelloProperties.class) //默认 HelloProperties放在容器中
public class HelloServiceAutoConfiguration {
@ConditionalOnMissingBean(HelloService.class)
@Bean
public HelloService helloService(){
HelloService helloService = new HelloService();
return helloService;
}
}
- HelloProperties.java
@ConfigurationProperties("com.flyyant")
public class HelloProperties {
private String prefix;
private String suffix;
public String getPrefix() {
return prefix;
}
public String getSuffix() {
return suffix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
}
- HelloService.java
/**
* 默认不放在容器中
*/
public class HelloService {
@Autowired
HelloProperties helloProperties;
public String sayHello(String name) {
return helloProperties.getPrefix() + ": " + name + ">>" + helloProperties.getSuffix();
}
}
- spring.factories
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.flyyant.hello.auto.HelloServiceAutoConfiguration
spring.factories的内容为什么这么写可以关注我看我粉丝文章中的springboot专栏
- 将项目打包安装到maven仓库
- 新建springboot项目
testcustomer
,引入依赖
<dependency>
<groupId>com.flyyant</groupId>
<artifactId>flyyant-hello-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
- 在
application.properties
中配置内容
com.flyyant.prefix=flyyant
com.flyyant.suffix=6666
这样配的原因是之前我们写的HelloProperties.java文件中我门定义了@ConfigurationProperties(“com.flyyant”)
- 新建controller文件
- HelloController.java
@RestController
public class HelloController {
@Autowired
HelloService helloService;
@GetMapping("/hello")
public String hello(){
String s = helloService.sayHello("张三");
return s;
}
}
- 运行,访问http://localhost:8080/hello