springboot自动配置、和带@EnableXXX开关的自动配置,自定义starter

 

1.创建普通maven项目,加入依赖,打包方式jar


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>2.1.1.release</version>
        </dependency>

2.创建普通javabean用于接收主配置中前缀为jwolf.id.generator,属性randomLength,prefix的配置

@ConfigurationProperties(prefix = "jwolf.id.generator")
public class IdGeneratorProperties {
    private Integer randomLength=6;
    private String prefix= "jwolf";
//省略getter setter方法

3.随便写的一个bean,要自定义自动注册的就是它

public class IdGenerator {
    private Integer randomlength;
    private String prefix;
    public void setRandomlength(Integer randomlength) {
        this.randomlength = randomlength;
    }
    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }
    public  String getPrefixTimeRandomId(){
        return prefix+System.currentTimeMillis()+new Random(randomlength).nextInt();
    }
    public  String getPrefixTimeId(){
        return prefix+System.currentTimeMillis();
    }
}

4.跟普通的配置bean没什么区别,关键是要作为一个独立的jar导入给其它项目使用,并不在@SpringBootApplication能扫描到的范围内,但是springboot会读取jar包META-INF里的spring.factories,需要在该文件里配置让spring自动注册该bean。测试:IDEA安装到maven或发布到nexus,其它项目引入其maven坐标 直接@Autowire注入即可使用

@Configuration
@ConditionalOnMissingBean(IdGenerator.class)
//开启自动配置,注册一个IdGeneratorProperties类型的配置bean到spring容器,同普通的@EnableAsync等开关一样
@EnableConfigurationProperties(IdGeneratorProperties.class) 
public class IdGeneratorConfiguration {
    @Autowired
    IdGeneratorProperties properties;
    @Bean
    public  IdGenerator getIdGenerator(){
        IdGenerator generator = new IdGenerator();
        generator.setRandomlength(properties.getRandomLength());
        generator.setPrefix(properties.getPrefix());
        return generator;
    }
}

5.常用的spring-boot-starter-data-redis等就是这么玩的,但还有一种带@EnableXXX开关的自动配置就可以无META-INF/spring.factories,需要自定义一个注解,注解中通过@Import来导入IdGenneratorConfiguration配置类,从而自动注册一个IdGennerator到spring容器. 这时需要主配置@EnableIdGenerator

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@ImportAutoConfiguration(IdGeneratorConfiguration.class)
public @interface EnableHttpClinet {
}
@RunWith(SpringRunner.class)
@SpringBootTest
@EnableIdGenerator
public class DemoApplicationTests {
    @Autowired
    IdGenerator idGenerator;
    @Test
    public void contextLoads() {
        System.out.println(idGenerator.getPrefixTimeRandomId());
        System.out.println(idGenerator.getPrefixTimeId());

    }

}

6.springboot的 @EnableWebMvc等都是用的这种方式,但springboot还有一种比这种更高大上一点的玩法如@EnableAsync

,此注解不是直接import的配置类,而是一个继承AdviceModeImportSelector的自定义selector

参考:https://www.jianshu.com/p/7fd7eeeccad0

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值