自定义Spring Boot Starter,并使用它
Spring Boot由众多Starter组成,随着版本的推移Starter家族成员也与日俱增。在传统Maven项目中通常将一些层、组件拆分为模块来管理,以便相互依赖复用,在Spring Boot项目中我们则可以创建自定义Spring Boot Starter来达成该目的。自定义一个Starter步骤如下:
1.使用Maven或者Gradle构建一个项目,Maven配置文件如下:
|
- buildscript {
- ext {
- springBootVersion = '1.5.9.RELEASE'
- }
- repositories {
- mavenCentral()
- }
- dependencies {
- classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
- }
- }
- apply plugin: 'java'
- apply plugin: 'eclipse'
- apply plugin: 'org.springframework.boot'
- apply plugin: 'maven-publish' //添加maven插件
- group = 'com.example'
- version = '0.0.1-SNAPSHOT'
- sourceCompatibility = 1.8
- repositories {
- mavenCentral()
- }
- dependencies {
- compile('org.springframework.boot:spring-boot-starter')
- //主要是添加这个依赖
- compile('org.springframework.boot:spring-boot-autoconfigure')
- testCompile('org.springframework.boot:spring-boot-starter-test')
- }
Userproperties如下:省略get,set方法
- @ConfigurationProperties(prefix = "user")
- public class Userproperties {
- private String name;
- private Integer age;
- }
- public class UserService {
- private Userproperties userproperties;
- public UserService(Userproperties userproperties) {
- this.userproperties = userproperties;
- }
- public void sayHello(){
- System.out.println("Hello---"+userproperties.getName()+"---"+userproperties.getAge());
- }
- @Configurable
- @EnableConfigurationProperties(Userproperties.class)
- @ConditionalOnProperty(prefix = "user", name = {"name", "age"})
- public class UserAutoConfig {
- @Autowired
- private Userproperties userproperties;
- @Bean
- public UserService userService() {
- UserService userService = new UserService(userproperties);
- return userService;
- }
- }
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.config.UserAutoConfig |
到这里就结束了,使用的时候配置user.name=”xxx”,user.age=33即可。
打包命令如下:
mvn:install 或者 gradle build(IDEA右侧build里面jar命令也可以)然后当本地jar引入即可参考:
- <dependency>
- <groupId>com.example</groupId>
- <artifactId>example-spring-boot-starter</artifactId>
- <version>1.0-SNAPSHOT</version>
- <scope>system</scope>
- <systemPath>/Users/henshao/Java/example-starter/target/example-spring-boot-starter-1.0-SNAPSHOT.jar</systemPath>
- </dependency>Gradle的是创建一个libs目录,在build.gradle加一句compile fileTree(dir: 'libs', include: '*.jar') 即可
- // 发布到本地Maven库和远程Maven服务器
- publishing {
- repositories {
- mavenLocal()
- maven {
- credentials {
- username xxxx
- password xxxx
- }
- url "https://xxxx.xx.com/"
- }
- }
- }