温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么定义一个spring boot starter

发布时间:2021-06-12 10:51:17 来源:亿速云 阅读:152 作者:小新 栏目:编程语言

这篇文章主要介绍了怎么定义一个spring boot starter,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

一、建立模块

名称规范:XXX-spring-boot-starter

二、编写Bean

public class BeanConfig {

    @Bean
    TestBean testBean(){
        TestBean testBean = new TestBean();
        return testBean;
    }

}

这里我们有一个BeanConfig类,通过它去注入一些Bean

三、将BeanConfig交给Spring容器

编写spring.factories: 创建resources\META-INF\spring.factories文件

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.config.BeanConfig

那么在启动时会通过AutoConfigurationImportSelector将BeanConfig注入到容器中。

四、打jar,生成maven依赖(略)

导入依赖即可以生效了。

如果想自定义一些配置怎么去做?

编写配置类:

@ConfigurationProperties("com.test") // 需要配合@EnableConfigurationProperties使用
public class BeanProperties {

    private String testName = "default-name";

    private Long telephoneNumber;
    // 必须有set方法
    public void setTestName(String testName) {
        this.testName = testName;
    }

    public void setTelephoneNumber(Long telephoneNumber) {
        this.telephoneNumber = telephoneNumber;
    }

    @PostConstruct
    void init(){
        String name = this.testName;
        System.out.println("-----------------------------"+name);
        Long telephoneNumber = this.telephoneNumber;
        System.out.println("-----------------------------"+telephoneNumber);
    }
}

其中的@ConfigurationProperties注解要和@EnableConfigurationProperties搭配使用(实际也是一个EnableConfigurationPropertiesRegistrar)

那么在BeanConfig上添加注解:@EnableConfigurationProperties(BeanProperties.class)

@EnableConfigurationProperties(BeanProperties.class)
public class BeanConfig {

    @Bean
    TestBean testBean(){
        TestBean testBean = new TestBean();
        return testBean;
    }

}

项目中引入依赖后,只需要在配置文件中指定值就可以了,这里的前缀要和@ConfigurationProperties指定的值相同

#com.test.test-name=zhangsan
com.test.telephone-number=12300000000

不指定则使用定义的默认值:

-----------------------------default-name
-----------------------------12300000000

当然,@ConfigurationProperties注解也不一定要和@EnableConfigurationProperties搭配使用,前提是spring容器要知道你的@ConfigurationProperties配置类

修改BeanConfig类,将注解改为@Import(BeanProperties.class)也是有效的。

@Import(BeanProperties.class)
public class BeanConfig {

    @Bean
    TestBean testBean(){
        TestBean testBean = new TestBean();
        return testBean;
    }

}

如果不通过SPI方式导入怎么做?

还是@Import注解方式,首先自定义注解:

@Target({java.lang.annotation.ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Import({BeanConfig.class})
public @interface StarterAnnotation {
}

这里Import导入了BeanConfig

然后项目中启动类加上注解@StarterAnnotation即可。

感谢你能够认真阅读完这篇文章,希望小编分享的“怎么定义一个spring boot starter”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI