本文介绍SpringBoot相关内容。和【跨考菌】一起加油吧~
如果你有收获,记得帮博主一键三连哦
starter:
1、这个场景需要使用到的依赖是什么?
2、如何编写自动配置
我们先随便打开一个stater观察其结构,可以发现里面除了META-INF文件之外,没有任何其他的java代码。
其实,这里的stater通过pom引入其对应的autoConfigurer
来实现的。
<dependencies>
<dependency>
<groupId>com.atguigu.startergroupId>
<artifactId>atguigu-spring-boot-starter-autoconfigurerartifactId>
<version>0.0.1-SNAPSHOTversion>
dependency>
dependencies>
HelloProperties.java:
@ConfigurationProperties(prefix = "atguigu.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;
}
}
HelloService.java:
public class HelloService {
HelloProperties helloProperties;
public HelloProperties getHelloProperties() {
return helloProperties;
}
public void setHelloProperties(HelloProperties helloProperties) {
this.helloProperties = helloProperties;
}
public String sayHellAtguigu(String name){
return helloProperties.getPrefix()+"-" +name + helloProperties.getSuffix();
}
}
HelloServiceAutoConfiguration.java:
@Configuration
@ConditionalOnWebApplication //web应用才生效
@EnableConfigurationProperties(HelloProperties.class) // 这里相当于将配置文件对应的参数和HelloProperties绑定,并将HelloProperties注册到bean中。
public class HelloServiceAutoConfiguration {
@Autowired
HelloProperties helloProperties;
@Bean
public HelloService helloService(){
HelloService service = new HelloService();
service.setHelloProperties(helloProperties);
return service;
}
}
classpath:META-INF/spring.factories:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.atguigu.starter.HelloServiceAutoConfiguration
pom引入自动配置模块:
<!--引入自动配置模块-->
<dependency>
<groupId>com.atguigu.starter</groupId>
<artifactId>atguigu-spring-boot-starter-autoconfigurer</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
pom引入自定义stater的依赖:
<!--引入自定义的starter-->
<dependency>
<groupId>com.atguigu.starter</groupId>
<artifactId>atguigu-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
配置文件配置属性:
atguigu.hello.prefix=ATGUIGU
atguigu.hello.suffix=HELLO WORLD
测试:
@RestController
public class HelloController {
@Autowired
HelloService helloService;
@GetMapping("/hello")
public String hello(){
return helloService.sayHellAtguigu("haha");
}
}