SpringBoot-写Starter

test-spring-boot-autoconfigure
在这里插入图片描述
pom引入

    <parent>
        <!-- 导入spring boot的web支持 -->
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>
    
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

配置文件类

@ConfigurationProperties(prefix = "test.hello")
public class HelloProperties {

    private String suffix;

    public String getSuffix() {
        return suffix;
    }

    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }
}

服务类

public class HelloService {

    HelloProperties helloProperties;

    public String sayHello(String name) {
        return "Hello " + name + "," + helloProperties.getSuffix();
    }

    public HelloProperties getHelloProperties() {
        return helloProperties;
    }

    public void setHelloProperties(HelloProperties helloProperties) {
        this.helloProperties = helloProperties;
    }
}

注册类

/**
 * web应用才生效
 */
@ConditionalOnWebApplication
/**
 * 让属性文件生效
 */
@EnableConfigurationProperties(HelloProperties.class)
/***
 * 声明是一个配置类
 */
@Slf4j
@Configuration
public class HelloServiceAutoConfiguration {

    @Autowired
    private HelloProperties helloProperties;

    @Bean
    public HelloService helloService() {
        log.info("开始注册HelloService Bean");
        HelloService helloService = new HelloService();
        helloService.setHelloProperties(helloProperties);
        return helloService;
    }
}

resources/META-INF下创建文件spring.factories

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.test.autoconfig.HelloServiceAutoConfiguration

test-spring-boot-starter
在这里插入图片描述
为空,pom.xml引入

        <dependency>
            <groupId>com.test</groupId>
            <artifactId>test-spring-boot-autoconfigure</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

配置类

测试在SpringBoot项目中,pom.xml引入自动配置项目

        <dependency>
            <groupId>com.test</groupId>
            <artifactId>test-spring-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

配置

test.hello.suffix=早上好

注入HelloService,即可使用。

    @Autowired
    private HelloService helloService;

参考 https://www.cnblogs.com/niumoo/p/11775009.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值