SpringBoot---制作一个starter

SpringBoot---制作一个starter

SpringBoot中引入的都是一个个starter,每个starter都是开箱即用,只需要简单的配置就能获取到starter中的各种功能,大大简化了开发,写一个简单的starter。

<!--官方的依赖格式是spring-boot-starter-xxx-->
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
<!--第三方的依赖格式是xxx-spring-boot-starter-->

1、写一个starter

写一个pojo类

这个pojo类用了lombok,所以使用了这个starter的工程也会有lombok的依赖。

package com.cgl.starter.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * @author cgl
 * @version 1.0
 * @date 2020/9/7 9:12
 */
@Data
@AllArgsConstructor
public class People {

    private Integer id;
    private String name;
    private String sex;
    private String age;
}

写一个配置类

这个配置类根据@ConditionalOnProperty注解,如果工程中有相应的配置,那么这个配置类生效。

package com.cgl.starter.config;

import com.cgl.starter.pojo.People;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author cgl
 * @version 1.0
 * @date 2020/9/7 9:15
 */
@Configuration
@ConditionalOnProperty(prefix = "start.people",name = "enabled",havingValue = "true")
public class PeopleConfig {

    //当这个配置类生效时,这个bean就在容器中
    @Bean
    public People p(){
        return new People(10010,"Jack","man","19");
    }
}

设置为自动配置类

在resources/META-INF/spring.factories中,把这个配置类设置为自动装配。

这个starter被引用后,这个配置类生效。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.cgl.starter.config.PeopleConfig

使用mvn install将starter安装到仓库中。

2、使用这个starter

在工程中导入starter.

<!--在pom导入starter-->
<dependency>
            <groupId>com.cgl</groupId>
            <artifactId>test-spring-boot-starter</artifactId>
            <version>0.0.1</version>
        </dependency>

starter中的配置类生效,开始查看配置文件中是否有对应条件。

在配置文件中加入这行配置,使starter配置类生效。

start.people.enabled=true

此时可以拿到starter中配置好的bean了。

@SpringBootTest
@RunWith(SpringRunner.class)
class TestSpringBootApplicationTests {

    @Autowired
    People people;

    @Test
    void contextLoads() {
        System.out.println(people);
    }

}


People(id=10010, name=Jack, sex=man, age=19)
原文地址:https://www.cnblogs.com/cgl-dong/p/13820754.html