总结

代码编写总共四步:

  1. 定义一个类,这个类将来需要通过“配置类”来实例化的Bean
  2. 定义一个属性类,并通过@ConfigurationProperties注解它。将来application.yml里能配置的属性,和该属性类的属性一一对应
  3. 定义一个配置类,通过@EnableConfigurationProperties将第2步的属性类注入IOC容器中;通过@Bean将第1步的类的对象注入IOC容器中
  4. 在resources 下面增加 META-INF/spring.factories,将第3步的配置类全路径名,写入org.springframework.boot.autoconfigure.EnableAutoConfiguration中
一、代码编写

第一步:定义 需要通过“配置类”来实例化的Bean



public class MsgService {

private String url;

private String content;

public MsgService(String url, String content) {
this.url = url;
this.content = content;
}

public String sendMsg() {
System.out.println("**********消息发送成功,地址=" + url + ",内容=" + content + "");
return "消息发送成功,地址=" + url + ",内容=" + content + "";
}

}


 

第二步: 定义 “属性类”

这里通过@ConfigurationProperties注解将配置文件的前缀为msg的配置信息与自身的属性绑定,所有在配置文件中能配置的属性都在MsgProperties类中封装着,配置文件能配置什么只需要看这个属性类的属性。



@ConfigurationProperties(prefix = "msg")
public class MsgProperties {
/**
* 消息发送地址
*/
private String url;
/**
* 发送内容
*/
private String content;

//get,set方法省略


 

第三步:定义 “配置类”

@Bean注解表明该方法实例化的对象会被加载到容器当中;

@ConditionalOnMissingBean注解指明当容器中不存在MsgService的对象时再进行实例化;

@EnableConfigurationProperties注解是使MsgProperties生效,也就是将MsgProperties类注入到IOC容器中。

@ConditionalOnClass 注解表明只有classpath下能找到MsgService类时才会构建这个Bean。



@Configuration
@ConditionalOnClass(MsgService.class)
@EnableConfigurationProperties(MsgProperties.class)
public class MsgConfiguration {
/**
* 注入属性类
*/
@Autowired
private MsgProperties msgProperties;

@Bean
@ConditionalOnMissingBean({MsgService.class})
public MsgService msgService() {
return new MsgService(msgProperties.getUrl(), msgProperties.getContent());
}
}


 

 

第四步:定义好spring.factories属性文件

要想实现自动配置,那么spring.factories属性文件是必不可少的,因为SpringBoot需要通过spring.factories找到需要实例化的配置类。然后通过SPI的方式来实例化。

所以,我们需要在resources 下面增加 META-INF/spring.factories



org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.jay.config.MsgConfiguration


 

二、打包上传到本地仓库

上面的步骤都搞好之后,我们这个自定义的starter模块差不多就可以用了,为了上其他项目可以引入我们的自定义的starter模块,我们需要通过mvn install命令将这个starter包上传到我们本地仓库或者私服。

 

三、其他项目引用该starter

1. 引入依赖



<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<!--自定义的starter-->
<dependency>
<groupId>com.jay</groupId>
<artifactId>springboot-custom-starter2</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>


 

2. 在application.properties文件中增加配置



msg.url=127.0.0.1
msg.content=nice to meet you


 

3.测试



@RestController
public class HelloWorldController {
@Autowired
private MsgService msgService;

@RequestMapping(value = "/testSendMsg")
public String testSendMsg() {
String sendMsg = msgService.sendMsg();
return sendMsg;
}
}


启动项目,访问接口,结果如下:

Springboot - 如何自定义一个starter模块_实例化