Spring Boot系列之自定义starter
1、创建spring boot项目,命名为mymsgstarter-spring-boot-starter。项目结构见图。其中MsgProperties、MsgAutoConfiguration、MsgService分别为配置属性类、配置类、和服务类。
2、配置属性类MsgProperties,使用@ConfigurationProperties(prefix = "com.mymsg")声明,并设置prefix前缀。定义属性类中的属性msg。
@ConfigurationProperties(prefix = "com.mymsg")
public class MsgProperties {
private String msg = "default msg";
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}}
3、服务类MsgService,定义msg属性,此类为普通的service,提供给其他服务调用。
public class MsgService {
private String msg;
public MsgService(String msg) {
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
4、自动配置类MsgAutoConfiguration。注入配置属性类,并把配置属性类中的msg值赋予给service中msg。
@Configuration
@EnableConfigurationProperties(MsgProperties.class)
@ConditionalOnClass(MsgService.class)
public class MsgAutoConfiguration {
@Autowired
private MsgProperties msgProperties;
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "com.mymsg",value = "enabled",matchIfMissing = true)
public MsgService msgService() {
return new MsgService(msgProperties.getMsg());
}
}
5、注册自动配置类spring.factories
org.springframework.data.repository.core.support.RepositoryFactorySupport=com.mypro.springboot.mymsgstarterspringbootstarter.MsgAutoConfiguration
6、install。在idea中的maven projects窗口,找到项目,lifecycle下选中install并执行,即可install jar包至本地maven仓库。
注意,maven setting中,MAVEN-Runner下的jdk要选择1.8,否则install报无效字符-paramters的异常。
另,pom.xml中的
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin>
</plugins>
</build>
要去掉,否则项目jar包的目录不合规范
7、新创建项目,在pom.xml中引入自定义starter的依赖,更新依赖包
<dependency>
<groupId>com.mypro.springboot</groupId>
<artifactId>mymsgstarter-spring-boot-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
8、编写测试类。
@RunWith(SpringRunner.class)
@SpringBootApplication
@ComponentScan(basePackages = {"com.mypro","com.myproject"})
public class MyMsgStarterTest {
@Autowired
private MsgService msgService;
@Test
public void test() {
System.out.println(msgService.getMsg());
}
}
9、测试结果1
配置属性类MsgProperties的msg的默认值为default msg,测试结果输出为default msg。
10、测试结果2
在application.properties中设置msg的值,com.mymsg.msg=hello world,测试结果输出为hello world