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

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

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

实现过程

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

public class PropertiesCondition implements Condition {

    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        Map<String, Object> annotationAttributes = annotatedTypeMetadata.getAnnotationAttributes(CustomConditionalOnProperty.class.getName());
        String name = String.valueOf(annotationAttributes.get("name"));

        // 期望值
        String expectedValue = String.valueOf(annotationAttributes.get("havingValue"));
        // 当前值
        String value = conditionContext.getEnvironment().getProperty(name);
        return Objects.equals(expectedValue, value);
    }
}

搭配上CustomConditionalOnProperty注解来使用

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Conditional({PropertiesCondition.class})
public @interface CustomConditionalOnProperty {
    /**
     * 配置名称
     *
     * @return
     */
    String name();

    /**
     * 值
     *
     * @return
     */
    String havingValue();

    /**
     * 缺省值
     *
     * @return
     */
    boolean defaultValueIfMissing() default false;
}

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

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

完结 撒花!!!

posted @ 2024-04-15 14:44  实习小生  阅读(16)  评论(0编辑  收藏  举报