天冷主要复习,
最近打算跟着大佬写组件,自己练习了一下
读取yml里面hello:name hello :address值
@ConfigurationProperties(prefix = "hello")
public class HelloProperties {
private String name;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "HelloProperties{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}
告诉Spring Boot要扫描并注册带有@ConfigurationProperties注解的类。这样,当Spring Boot启动时,它会自动创建这些类的实例,并将配置文件中的属性值绑定到这些实例的属性上。后面带一个指定值,
@Configuration
@EnableConfigurationProperties(value = HelloProperties.class)
public class HelloServiceAutoConfiguration {
private HelloProperties helloProperties;
public HelloServiceAutoConfiguration(HelloProperties helloProperties) {
this.helloProperties = helloProperties;
}
@ConditionalOnMissingBean//不存在bean才创建
@Bean
public HelloService helloService(HelloProperties helloProperties){
return new HelloService(helloProperties.getName(), helloProperties.getAddress());
}
}
在配置包下面的INTA-INF
创建一个spring.factories文件,将类注册到springboot这个东西里面org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.config.HelloServiceAutoConfiguration
把上面项目打包创建一个信项目,引入maven坐标,直接使用
/**
* @Author 菠萝哥
**/
@RestController
@RequestMapping("/hello")
public class helloController {
@Autowired
private HelloService helloService;
@GetMapping
public String sayHello(){
return helloService.sayHello();
}
}