1. 程式人生 > >spring容器啟動就獲得實現指定介面的beanMap

spring容器啟動就獲得實現指定介面的beanMap

package cn.baozun.crm.listener;


import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;


import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;


import cn.baozun.crm.service.api.common.IMobile;
import cn.baozun.crm.util.ProxyToTarget;

// IMObile  換成指定介面就行了  在application。xml配置 listenner bean即可

public class ContextBeanListener implements ApplicationListener<ContextRefreshedEvent>{


@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
        // 根容器為Spring容器  
        if(event.getApplicationContext().getParent()==null){  
            Map<String,Object> beans = event.getApplicationContext().getBeansWithAnnotation(org.springframework.stereotype.Component.class );
            HashMap<String,Object> map= new HashMap<String,Object>();
            for (Entry<String,Object> entry : beans.entrySet()) {
String key = entry.getKey();
Object obj  =  entry.getValue();
try {
Object target = ProxyToTarget.getTarget(obj);
if(target instanceof IMobile){
map.put(key, target);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
            
         
        }

}


}

//將spring  代理物件轉換成  真是物件

package cn.baozun.crm.util;


import java.lang.reflect.Field;


import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.aop.framework.AopProxy;
import org.springframework.aop.support.AopUtils;


public class ProxyToTarget {
public static Object getTarget(Object proxy) throws Exception {
if (!AopUtils.isAopProxy(proxy)) {
return proxy;// 不是代理物件
}


if (AopUtils.isJdkDynamicProxy(proxy)) {
return getJdkDynamicProxyTargetObject(proxy);
} else { // cglib
return getCglibProxyTargetObject(proxy);
}
}


private static Object getCglibProxyTargetObject(Object proxy) throws Exception {
Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
h.setAccessible(true);
Object dynamicAdvisedInterceptor = h.get(proxy);
Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
advised.setAccessible(true);
AdvisedSupport advisedSupport = (AdvisedSupport) advised.get(dynamicAdvisedInterceptor);
Object target = advisedSupport.getTargetSource().getTarget();
return target;
}


private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {
Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
h.setAccessible(true);
AopProxy aopProxy = (AopProxy) h.get(proxy);
Field advised = aopProxy.getClass().getDeclaredField("advised");
advised.setAccessible(true);
Object target = ((AdvisedSupport) advised.get(aopProxy)).getTargetSource().getTarget();
return target;
}


}