标签:String 自定义 boot class HelloworldService words public Starter SprinigBoot
自定义Starter
是什么
starter可以理解是一组封装好的依赖包,包含需要的组件和组件所需的依赖包,使得使用者不需要再关注组件的依赖问题
所以一个staerter包含
- 提供一个autoconfigure类
- 提供autoconfigure类的依赖
怎么做
创建starter大概需要
- 需要一个配置类bean,来填充配置
- 获取配置信息,注册到容器
- 将配置类加到自动配置
导入自动装配和Spring boot依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
创建一个bean
@Data
public class HelloworldService {
private String words;
public String sayHello() {
return "hello, " + words;
}
}
创建peoperties类来自定义需要的参数,用来接收properties或者yml里的配置
//helloword就是配置的前缀
@ConfigurationProperties(prefix = "helloword")
public class HelloworldProperties {
public static final String DEFAULT_WORDS = "world";
//这个值就是helloword.words
private String words = DEFAULT_WORDS;
public String getWords() {
return words;
}
public void setWords(String words) {
this.words = words;
}
}
创建configureation类来注册bean
将配置的参数注入到bean里,在注册到容器
@Configuration
//指定条件成立的情况下自动配置类生效(往哪装配)
@ConditionalOnClass(HelloworldService.class)
//让xxxProperties生效加入到容器中
@EnableConfigurationProperties(HelloworldProperties.class)
public class HelloworldAutoConfiguration {
// 注入属性类
@Autowired
private HelloworldProperties hellowordProperties;
@Bean
// 当容器没有这个 Bean 的时候才创建这个 Bean
@ConditionalOnMissingBean(HelloworldService.class)
public HelloworldService helloworldService() {
HelloworldService helloworldService = new HelloworldService();
helloworldService.setWords(hellowordProperties.getWords());
return helloworldService;
}
}
在启动类里标明需要自动装配
@EnableAutoConfiguration//开启自动装配
@ComponentScan({"test"})
public class TestApplication {
}
最后是指定装配哪个配置类
在resources目录下创建META-INF
文件夹
然后创建spring.factories
标注需要装配的配置类
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
test.config.HelloworldAutoConfiguration
最后就可以用这个starter了
首先导入这个starter
<dependency>
<groupId>org.example</groupId>
<artifactId>test-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
然后导入HelloworldService
这个bean
和在yml里配置参数
helloword:
words : hello
就完成了
标签:String,自定义,boot,class,HelloworldService,words,public,Starter,SprinigBoot 来源: https://www.cnblogs.com/aruo/p/15733194.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。