業務需求:緩存頁面,展現須要緩存的全部對象,每類對象在字典表中有編碼對應,點擊某個對象能夠緩存某類對象,每類對象都有本身的緩存runner(弱弱的說一句,本人看到這裏的第一反應就是if-else,捂臉中。。。。。。。。。。。)java
方法:經經理指導,使用BeanPostProcessor接口spring
邏輯:自定義一個標籤,spring實例化全部bean以後,取出每一個便籤的所對應的code,以及當前的code對應的runner放在一個管理器裏面,使用時從管理器中取出緩存
實例說明:ide
自定義標籤post
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); } }
測試結果spa