• 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);
        }
    }

    测试结果

  • 相关阅读:
    20169220 2016-2017-2 <网络攻防实践> 课程总结
    20169220 <网络攻防实践> 第十四周实验—免杀
    20169220 <网络攻防实践> 第十二周实验—SQL注入
    20169220 <网络攻防实践> 第十一周实验—SQL注入+TCP/IP攻击
    20169220 <网络攻防实践> 第十周实验—Nmap+Wireshark+缓冲区溢出漏洞
    20169220 <网络攻防实践> 第九周实验——Nmap
    20169220 <网络攻防实践> 第八周实验——网络攻防虚拟机环境搭建
    20169220 <网络攻防实践> 第七周学习总结
    20169220 <网络攻防实践> 第六周学习总结
    20169220 <网络攻防实践> 第五周学习总结
  • 原文地址:https://www.cnblogs.com/Cassie-wang/p/10968204.html
Copyright © 2020-2023  润新知