- 1.创建boot-07-hello-starter-autoconfigure模块
- 1.1 创建实体类HelloProperties
- 1.2 创建服务HelloService
- 1.3 创建配置类HelloServiceAutoConfiguration
- 1.4 在resources/meta-INF目录下创建spring.factories文件
- 1.5 运行clean和install使之放入maven仓库中
- 2. 创建boot-07-hello-starter模块
- 2.1 在pom.xml文件中引入boot-07-hello-starter-autoconfigure依赖
- 2.2 运行clean和install使之放入maven仓库中
- 3. 创建boot-07-hello-test进行测试
- 3.1 引入boot-07-hello-starter依赖
- 3.2 创建RestController测试
- 3.3 需要在配置文件中添加内容
- 4. 运行测试
- 5. 代码总思路
@ConfigurationProperties("szp.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;
}
}
1.2 创建服务HelloService
public class HelloService {
@Autowired
HelloProperties helloProperties;
public String sayHello(String userName){
return helloProperties.getPrefix() + ": " + userName + ">" + helloProperties.getSuffix();
}
}
1.3 创建配置类HelloServiceAutoConfiguration
@Configuration
@ConditionalOnMissingBean(HelloService.class)
@EnableConfigurationProperties(HelloProperties.class) //默认HelloProperties放在容器中
//当容器中没有HelloService的时候将其放入容器
public class HelloServiceAutoConfiguration {
@Bean
public HelloService helloService(){
return new HelloService();
}
}
1.4 在resources/meta-INF目录下创建spring.factories文件
#使之可以自动加载需要的配置文件 # Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration= com.szp.hello.auto.HelloServiceAutoConfiguration1.5 运行clean和install使之放入maven仓库中 2. 创建boot-07-hello-starter模块 2.1 在pom.xml文件中引入boot-07-hello-starter-autoconfigure依赖
com.szp
boot-07-hello-starter-autoconfigure
0.0.1-SNAPSHOT
2.2 运行clean和install使之放入maven仓库中
3. 创建boot-07-hello-test进行测试
3.1 引入boot-07-hello-starter依赖
org.szp
boot-07-hello-starter
1.0-SNAPSHOT
3.2 创建RestController测试
@RestController
public class HelloController {
@Autowired
HelloService helloService;
@GetMapping("hello")
public String sayHello(){
String s = helloService.sayHello("张三");
return s;
}
}
3.3 需要在配置文件中添加内容
szp.hello.prefix=szp szp.hello.suffix=world4. 运行测试 5. 代码总思路
前面的操作可使得引入maven依赖
配置类使得当容器中没有HelloService时将其放入容器,使其可以自动注入。且将HelloProperties放入容器中使其生效。
HelloProperties中@ConfigurationProperties(“szp.hello”)表明了会从配置文件的szp.hello获取prefix和suffix的内容。
HelloController中自动注入了HelloService,HelloService中又自动注入了HelloProperties。



