spring容器启动就获得实现指定接口的beanMap

来源:互联网 发布:安卓模拟器优化 编辑:程序博客网 时间:2024/04/29 10:23
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;
}


}



0 0
原创粉丝点击