Skip to content

Instantly share code, notes, and snippets.

@logicjwell
Created April 28, 2019 03:51
Show Gist options
  • Save logicjwell/edb6fc482d8005519a109a6eb6649cb5 to your computer and use it in GitHub Desktop.
Save logicjwell/edb6fc482d8005519a109a6eb6649cb5 to your computer and use it in GitHub Desktop.
[springboot中自定义配置] #starter #自定义
@Configuration
@EnableConfigurationProperties(value = { TokenAutoConfiguration.TokenProperties.class })
@ConditionalOnBean(RestTemplate.class)
public class TokenAutoConfiguration {
@Autowired
TokenProperties properties;
@Bean
public TokenService tokenService(RestTemplate restTemplate){
return new TokenService(properties.service, restTemplate);
}
@ConfigurationProperties(prefix = "huacai.token")
@Data
public class TokenProperties implements java.io.Serializable {
String service;
}
}
关键点:
1. @EnableConfigurationProperties(value = { TokenAutoConfiguration.TokenProperties.class }) //指定装载自定义配置项的容器
2. @ConditionalOnBean(RestTemplate.class) //依据条件装载自定义配置项
3. @ConfigurationProperties(prefix = "huacai.token") //自定义配置项的前缀
在一般的springboot工程里,只有这个java class 就可以在springboot启动时装载自定义配置项。而如果是要封装成starter,从客户工程的配置文件里装载自定义配置项,需要在starter工程创建/resources/META-INF/spring.factories文件:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.huacai.base.config.TokenAutoConfiguration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment