自定义核心装配依赖
准备一创建一个maven项目
注意命名一定要规范,不能用Spring-Boot开头,用自定义的名称开头
按照文档说的
thirdpartyproject-spring-boot-starter.
项目结构
配置pom.xml 添加 父标签 和两个依赖包
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
</dependencies>
第一步: 编写Properties工具类
/**
* @author hong
* 自定义编写的工具类,可以参照springboot内嵌自动装配中的ServerProperties
*
* @ConfigurationProperties是用来对外暴露属性的写法,使得开发者可以在全局变量中修改的
*/
//prefix = "liuhstar" 是在配置文件中的引用
@ConfigurationProperties(prefix = "liuhstar")
public class HelloProperties {
private String word="hello world";
//只要有get和set方法,开发者就可以获取和修改
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
}
第二步: 编写接口和实现类
因为这里只是打印一句话所有声明很简单,也只要 一个就行了
/**
* @author hong
* 接口
*/
public interface Helloservice {
void sayHello();
}
/**@author hong
* 实现类
*/
public class HelloServiceImpl implements Helloservice {
//导入我们的工具类
@Autowired
private HelloProperties helloProperties;
/**
* 具体的方法体
*/
@Override
public void sayHello() {
System.out.println("ALAN SAY:"+helloProperties.getWord());
}
}
第三步: 编写配置类 【关键】
/**
* @author hong
* 定义一个配置类
*
* 模拟自动装配过程
* 一层层的判断如果符合就获取到实例然后 @Bean到我们的spring ioc容器当中
*/
@Configuration
//添加条件,判断当前classpath下是否有指定的类
@ConditionalOnClass(HelloProperties.class)
//开启自动配置 这里很关键,是将我们前面配置的工具类的@ConfigurationProperties注解生效
@EnableConfigurationProperties(HelloProperties.class)
public class HelloAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public Helloservice helloservice(){
return new HelloServiceImpl();
}
}
第四步【关键】: 创建一个META-INF文件夹 编写配置spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
starter.hello.HelloAutoConfiguration
最终的项目结构
最后一步,install
测试:创建一个普通的SpringBoot项目
导入刚刚install自定义依赖
结果