自定义 spring-boot-stater

October 17, 2018

spring boot stater

通过使用Spring Boot Starter将一些层、组件拆分为模块来管理,以便相互依赖复用。

自定义

1、创建一个Maven项目

首先自定义一个Maven项目,pom.xml中引入依赖。

            <dependency>
                <!-- Import dependency management from Spring Boot -->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>1.5.2.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

这里说下artifactId的命名问题,Spring 官方 Starter通常命名为spring-boot-starter-{name}spring-boot-starter-webSpring官方建议非官方Starter命名应遵循{name}-spring-boot-starter的格式.

2、创建一个简单的Starter

提供一个简单的Stater,提供一个Service,包含一个能够将字符串加上前后缀的方法String wrap(String word)。

public class DemoService {

	private String prefix;
	private String suffix;

	public DemoService(String prefix, String suffix) {
		this.prefix = prefix;
		this.suffix = suffix;
	}
	public String wrap(String word) {
		return prefix + word + suffix;
	}
}

前缀、后缀通过读取application.properties(yml)内的参数获得。

@ConfigurationProperties("demo.service")
public class DemoServiceProperties {
	private String prefix;
	private String suffix;
	#省略 set 和 get
}

编写AutoConfigure类。

@Configuration
@ConditionalOnClass(DemoService.class)
@EnableConfigurationProperties(DemoServiceProperties.class)
public class DemoAutoConfigure {

	@Autowired
	private DemoServiceProperties demoServiceProperties;


	@Bean
	@ConditionalOnMissingBean
	@ConditionalOnProperty(prefix = "demo.service",value = "enabled",havingValue = "true")
	DemoService demoService(){
		return new DemoService(demoServiceProperties.getPrefix(),demoServiceProperties.getSuffix());
	}
}

解释下用到的几个和Starter相关的注解:

  • @ConditionalOnClass,当classpath下发现该类的情况下进行自动配置。
  • @ConditionalOnMissingBean,当Spring Context中不存在该Bean时。
  • @ConditionalOnProperty(prefix = "example.service",value = "enabled",havingValue = "true"),当配置文件中example.service.enabled=true

更多相关注解,建议阅读官方文档部分

最后一步,在resources/META-INF/下创建spring.factories文件,内容供参考下面:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.demospringbootstarter.DemoAutoConfigure

执行mvn install 打包安装。

使用

1、新建一个新的Spring Boot项目

stater的依赖加入项目中。

        <dependency>
            <groupId>com.example</groupId>
            <artifactId>demo-spring-boot-starter</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

创建application.properties,进行配置

demo.service.enabled=true
demo.service.prefix=####
demo.service.suffix=@@@@

使用

    @Autowired
	private DemoService demoService;

	@GetMapping("/input/{word}")
	public String input(@PathVariable("word") String word){
		return demoService.wrap(word);
	}

原理

总结下Starter的工作原理.

  • Spring Boot在启动时扫描项目所依赖的JAR包,寻找包含spring.factories文件的JAR
  • 根据spring.factories配置加载AutoConfigure
  • 根据 @Conditional注解的条件,进行自动配置并将Bean注入Spring Context

参考文档


LRF 记录学习、生活的点滴