资讯专栏INFORMATION COLUMN

编写Spring boot自动配置

PAMPANG / 2930人阅读

摘要:背景学习的自动配置对于了解整个后端代码运行流程非常重要只有在了解是如何配置的情况下才能在项目的配置中不那么举步维艰假如我们编写了一个用于处理文件信息的工具类那么我们可以如下操作工具步骤创建一个普通的项目注意其中的和这两项将对应以后使用的依赖

背景

学习spring boot的自动配置对于了解整个后端代码运行流程非常重要,只有在了解spring boot是如何配置的情况下,才能在项目的配置中不那么举步维艰.

START

假如我们编写了一个用于处理文件信息的工具类,那么我们可以如下操作

工具

IntelliJ IDEA 2018

步骤
1.创建一个普通的spring boot项目

注意其中的Group和Artifact,这两项将对应以后使用的依赖参数

</>复制代码

  1. xyz.crabapple
  2. begonia
  3. 0.0.1-SNAPSHOT
2.项目的目录结构

3.现在我们主要代码需要写在begonia目录下

4.代码解释

BegoniaApplication 为spring boot自己生成的入口类所在的java文件.

Tool 是我的工具类具体实现

</>复制代码

  1. public class Tool {
  2. public String prefix;
  3. public Tool(String prefix) {
  4. this.prefix = prefix;
  5. }
  6. /**
  7. * 计算时间戳
  8. * @return 时间戳+五位随机大写字母
  9. */
  10. public String getStamp() {
  11. String prefix = String.valueOf(new Date().getTime());
  12. prefix=prefix.substring(2,prefix.length());
  13. char[] arr = new char[5];
  14. Random random = new Random();
  15. for (int i = 0; i < 5; i++)
  16. arr[i] = (char) (65 + random.nextInt(26));
  17. String Suffix = String.valueOf(arr);
  18. return prefix + Suffix;
  19. }

ToolProperties充当配置类和application.properties的桥,即它从application.properties中取具体的配置信息,而真正的配置类需要再到ToolProperties去取.

</>复制代码

  1. @ConfigurationProperties(prefix = "Tool")
  2. public class ToolProperties {
  3. private String prefix;
  4. public String getPrefix() {
  5. return prefix;
  6. }
  7. public void setPrefix(String path) {
  8. this.prefix = path;
  9. }
  10. }

ToolAutoConfiguration是我的具体配置类

</>复制代码

  1. @Configuration
  2. @EnableConfigurationProperties(ToolProperties.class)
  3. @ConditionalOnClass(Tool.class)
  4. @ConditionalOnProperty(prefix = "Tool", name="open" ,havingValue="true")
  5. public class ToolAutoConfiguration {
  6. @Autowired
  7. ToolProperties toolProperties;
  8. @Bean
  9. public Tool autoConfiger(){
  10. System.out.println("Tool工具已启动");
  11. System.out.println(toolProperties.getPrefix());
  12. return new Tool(toolProperties.getPrefix());
  13. }
  14. }

1.@Configuration 表示这是一个配置类,作用等同于@Component.
以下三个注解都是条件注解,如果有一个不满足条件,自动配置就不会运行.
2.@EnableConfigurationProperties(ToolProperties.class)
表示配置类的自动配置必须要求ToolProperties.class的存在
3.@ConditionalOnClass(Tool.class)
要求功能类存在.
4.@ConditionalOnProperty(prefix = "Tool", name="open" ,havingValue="true")
查看@ConditionOnProperty

</>复制代码

  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target({ ElementType.TYPE, ElementType.METHOD })
  3. @Documented
  4. @Conditional(OnPropertyCondition.class)
  5. public @interface ConditionalOnProperty {
  6. /**
  7. * Alias for {@link #name()}.
  8. * @return the names
  9. */
  10. String[] value() default {};
  11. /**
  12. * A prefix that should be applied to each property. The prefix automatically ends
  13. * with a dot if not specified.
  14. * @return the prefix
  15. */
  16. String prefix() default "";
  17. /**
  18. * The name of the properties to test. If a prefix has been defined, it is applied to
  19. * compute the full key of each property. For instance if the prefix is
  20. * {@code app.config} and one value is {@code my-value}, the fully key would be
  21. * {@code app.config.my-value}
  22. *

  23. * Use the dashed notation to specify each property, that is all lower case with a "-"
  24. * to separate words (e.g. {@code my-long-property}).
  25. * @return the names
  26. */
  27. String[] name() default {};
  28. /**
  29. * The string representation of the expected value for the properties. If not
  30. * specified, the property must not be equals to {@code false}.
  31. * @return the expected value
  32. */
  33. String havingValue() default "";
  34. /**
  35. * Specify if the condition should match if the property is not set. Defaults to
  36. * {@code false}.
  37. * @return if should match if the property is missing
  38. */
  39. boolean matchIfMissing() default false;
  40. /**
  41. * If relaxed names should be checked. Defaults to {@code true}.
  42. * @return if relaxed names are used
  43. */
  44. boolean relaxedNames() default true;
  45. }

prefix和name拼凑起来表示application.properties的配置信息key,例如我的配置信息为Tool.open=true,那么@ConditionalOnProperty(prefix = "Tool", name="open" ,havingValue="true")就表示配置信息中有这个key就为true,即满足条件,在此条件下若等于注解中havingValue的值,则该注解最终的结果为true.

最后我们需要注册自己的配置类

在/src/main目录下创建META-INF目录,并其下创建spring.factories文件,其实spring.factories文件就是一个.properties文件.

新建好后,在其中按如下方式书写

</>复制代码

  1. org.springframework.boot.autoconfigure.EnableAutoConfiguration=
  2. xyz.crabapple.begonia.ToolAutoConfiguration

第一行的org.springframework.boot.autoconfigure.EnableAutoConfiguration就是一个key,第二行的xyz.crabapple.begonia.ToolAutoConfiguration就是我们的自动配置类,即value.配置类还可以按需添加.例如我们找一个依赖看一看

找到一个spring boot自带的依赖,可以看到其书写方式,供大家参考.

</>复制代码

  1. # Initializers
  2. org.springframework.context.ApplicationContextInitializer=
  3. org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,
  4. org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer
END

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72958.html

相关文章

  • Spring Boot 入门(一)

    摘要:简介简化应用开发的一个框架整个技术栈的一个大整合开发的一站式解决方案微服务,微服务架构风格服务微化一个应用应该是一组小型服务可以通过的方式进行互通单体应用微服务每一个功能元素最终都是一个可独立替换和独立升级的软件单元环境准备推荐及以上以上版 1、Spring Boot 简介简化Spring应用开发的一个框架; 整个Spring技术栈的一个大整合; J2EE开发的一站式解决方案; 2、微...

    zhaochunqi 评论0 收藏0
  • spring boot - 收藏集 - 掘金

    摘要:引入了新的环境和概要信息,是一种更揭秘与实战六消息队列篇掘金本文,讲解如何集成,实现消息队列。博客地址揭秘与实战二数据缓存篇掘金本文,讲解如何集成,实现缓存。 Spring Boot 揭秘与实战(九) 应用监控篇 - HTTP 健康监控 - 掘金Health 信息是从 ApplicationContext 中所有的 HealthIndicator 的 Bean 中收集的, Spring...

    rollback 评论0 收藏0
  • Spring Boot 最流行的 16 条实践解读!

    摘要:来源是最流行的用于开发微服务的框架。以下依次列出了最佳实践,排名不分先后。这非常有助于避免可怕的地狱。推荐使用构造函数注入这一条实践来自的项目负责人。保持业务逻辑免受代码侵入的一种方法是使用构造函数注入。 showImg(https://mmbiz.qpic.cn/mmbiz_jpg/R3InYSAIZkHQ40ly9Oztiart2lESCyjCH0JwFRp3oErlYobhibM...

    Ethan815 评论0 收藏0
  • 第二十八章:SpringBoot使用AutoConfiguration自定义Starter

    摘要:代码如下所示自定义业务实现恒宇少年码云消息内容是否显示消息内容,我们内的代码比较简单,根据属性参数进行返回格式化后的字符串。 在我们学习SpringBoot时都已经了解到starter是SpringBoot的核心组成部分,SpringBoot为我们提供了尽可能完善的封装,提供了一系列的自动化配置的starter插件,我们在使用spring-boot-starter-web时只需要在po...

    fasss 评论0 收藏0
  • 慕课网_《Spring Boot热部署》学习总结

    时间:2017年12月01日星期五说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.com 教学源码:无 学习源码:https://github.com/zccodere/s... 第一章:课程介绍 1-1 课程介绍 热部署的使用场景 本地调式 线上发布 热部署的使用优点 无论本地还是线上,都适用 无需重启服务器:提高开发、调式效率、提升发布、运维效率、降低运维成本 前置...

    Channe 评论0 收藏0

发表评论

0条评论

PAMPANG

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<