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