自定义一个Starter主要分两部分:
- 一是自动配置所需要的类,包括自动配置类、JavaConfig以及在spring.factories中声明自动配置类(自动配置所需要的类不是必须的,可以不要)
- 二是实际的依赖项
具体实现:
1、 建一个SpringBoot项目(Maven项目也可),导入spring-boot-autoconfigure依赖(spring-boot-starter也可)
2、编写一个配置类HelloServiceProperties,读取yml中hello.msg的值,默认值是world
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
//如果@ConfigurationProperties是在第三方包中,那么@component是不能注入到容器的。
//只有@EnableConfigurationProperties才可以注入到容器。
//也就是说,如果我们自己定义的这个Starter是要在别的项目中引用的,
//那么这里用@Component注解无效,必须在AutoConfiguration类上面加上@EnableConfigurationProperties
@ConfigurationProperties(prefix = "hello")
public class HelloServiceProperties {
private static final String MSG = "world";
private String msg = MSG;
public String getMsg() {
return msg;
}
public void setMsg(String msg)