zoukankan      html  css  js  c++  java
  • Spring实例化bean之后的处理, 关于BeanPostProcessor接口的使用

    业务需求:缓存页面,展示需要缓存的所有对象,每类对象在字典表中有编码对应,点击某个对象可以缓存某类对象,每类对象都有自己的缓存runner(弱弱的说一句,本人看到这里的第一反应就是if-else,捂脸中。。。。。。。。。。。)

    方法:经经理指导,使用BeanPostProcessor接口

    逻辑:自定义一个标签,spring实例化所有bean之后,取出每个便签的所对应的code,以及当前的code对应的runner放在一个管理器里面,使用时从管理器中取出

     实例说明:

    自定义标签

    import static java.lang.annotation.ElementType.METHOD;
    import static java.lang.annotation.ElementType.PARAMETER;
    import static java.lang.annotation.ElementType.TYPE;
    import static java.lang.annotation.RetentionPolicy.RUNTIME;
    
    import java.lang.annotation.Documented;
    import java.lang.annotation.Retention;
    import java.lang.annotation.Target;
    
    import org.springframework.stereotype.Component;
    
    @Documented
    @Retention(RUNTIME)
    @Target({ TYPE, METHOD, PARAMETER })
    @Component
    public @interface CacheCode {
        String code() default "";
    }

    不同类上面添加标签(根据自己业务放在类上)

    import org.springframework.stereotype.Component;
    
    import com.*.cache.annotation.CacheCode;
    
    @Component
    @CacheCode(code = "1001")
    public class Test1 implements Test{
    
        @Override
        public void test() {
            System.out.println("调用测试1");
            
        }
    
    }
    import org.springframework.stereotype.Component;
    
    import com.*.cache.annotation.CacheCode;
    
    @Component
    @CacheCode(code = "1002")
    public class Test2 implements Test{
    
        @Override
        public void test() {
        System.out.println("调用测试2");
      } }
    public interface Test {
        
        public void test();
    }

    管理器

    @Component
    public class CacheManager implements BeanPostProcessor{
        
        private Map<String, Test> runners = new HashMap<String, Test>();
        
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            Class<? extends Object> persistentClass = bean.getClass();
            CacheCode cacheCode = AnnotationUtils.findAnnotation(persistentClass, CacheCode.class);
            if (null != cacheCode) {
                String code = cacheCode.code();
                Test runner = (Test)bean;
                runners.put(code, runner);
            }
            return bean;
        }
        
        public Test getRunner(String code) {
            return runners.get(code);
        }
    }

    测试结果

  • 相关阅读:
    不需重新编译php,安装postgresql扩展(pgsql和pdo_pgsql)
    css如何实现水平垂直居中
    win系统DOS批处理命令:每日根据定时计划,弹出相应的提醒
    使用navicat连接mysql连接错误:Lost connection to Mysql server at 'waiting for initial communication packet'
    mysql域名解析引起的远程访问过慢?
    Jquery封装: 地区选择联动插件
    Jquery封装: WebSocket插件
    Jquery封装:下拉框插件
    如何在微信小程序中使用阿里字体图标
    轻量级进度条 – Nprogress.js
  • 原文地址:https://www.cnblogs.com/Cassie-wang/p/10968204.html
Copyright © 2011-2022 走看看