经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring » 查看文章
SSM使用自定义ConditionalOnProperty实现按需加载spring bean
来源:cnblogs  作者:实习小生  时间:2024/4/15 14:46:26  对本文有异议

SSM使用自定义ConditionalOnProperty实现按需加载spring bean

背景: 公司提供的系统框架是SSM架构,SSM架构是没有springboot的ConditionalOnProperty注解的,而我们的系统是在很多区县部署的,每个区县会有一些定制化需求,其中有一个类只在一个区县里用得到,所以打算采用按需加载bean的方式。

实现过程

首先SSM里面是有Condition接口的,该接口的主要功能是实现spring在加载bean的时候对类进行检查,如果满足条件的话才会加载到spring容器里面,具体的条件和逻辑是靠子类实现的
所以我们创建了一个Condition的实现类PropertiesCondition

  1. public class PropertiesCondition implements Condition {
  2. @Override
  3. public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
  4. Map<String, Object> annotationAttributes = annotatedTypeMetadata.getAnnotationAttributes(CustomConditionalOnProperty.class.getName());
  5. String name = String.valueOf(annotationAttributes.get("name"));
  6. // 期望值
  7. String expectedValue = String.valueOf(annotationAttributes.get("havingValue"));
  8. // 当前值
  9. String value = conditionContext.getEnvironment().getProperty(name);
  10. return Objects.equals(expectedValue, value);
  11. }
  12. }

搭配上CustomConditionalOnProperty注解来使用

  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target({ElementType.TYPE})
  3. @Documented
  4. @Conditional({PropertiesCondition.class})
  5. public @interface CustomConditionalOnProperty {
  6. /**
  7. * 配置名称
  8. *
  9. * @return
  10. */
  11. String name();
  12. /**
  13. * 值
  14. *
  15. * @return
  16. */
  17. String havingValue();
  18. /**
  19. * 缺省值
  20. *
  21. * @return
  22. */
  23. boolean defaultValueIfMissing() default false;
  24. }

最后在我们需要的地方使用

  1. @Component
  2. @CustomConditionalOnProperty(name = "task.auto.enable",havingValue = "1")

完结 撒花!!!

原文链接:https://www.cnblogs.com/sxxs/p/18135947

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号