获取Spring加载的实例bean/获取注解Beam


1,编写工具类

 

package com.cfwx.rox.web.business.essence.util;

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

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 获取spring的注入bean 工具类
 * @author JSW
 *
 */
public class SpringContextUtil implements ApplicationContextAware
{
    
    private static  ApplicationContext context = null;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        context = applicationContext;
    }
    
    /**
     * 获取在*.xml文件中有注入的bean
     * @param beanName
     * @return
     */
    @SuppressWarnings("unchecked")
    public static  T getBean(String beanName){
        return (T) context.getBean(beanName);
    }

    /**
     * 获取到的类的实例对象
     */
    private Map classInstances;
    
    /**
     * 获取到的类的实例对象 指定spring注解的类对象
     */
    public Map getClassInstances() {
        if(this.classInstances == null){
            init();
        }
        return this.classInstances;
    }
    
    
    
    @SuppressWarnings("static-access")
    public void init(){
        if(this.context == null){
            return;
        }
        if(this.classInstances == null){
            this.classInstances = new HashMap();
        }
        
        Map beansWithAnnotationMap = this.context.getBeansWithAnnotation(org.springframework.stereotype.Service.class);
        
        Class clazz = null;
        for(Map.Entry entry : beansWithAnnotationMap.entrySet()){
            clazz = entry.getValue().getClass();//获取到实例对象的class信息
            Class  [] interfaces = clazz.getInterfaces();
            for(Class  aInterface : interfaces){
                //接口实例名(只是将接口的首字母换成小写)
                String aInterfaceSimpleName = getDefaultInstanceName(aInterface);
                classInstances.put(aInterfaceSimpleName, entry.getValue());
            }
        }
    }
    
    /**
     * 根据这个类来获取默认的实例名(默认:将首字母换成小写)
     * @param clazz  类信息
     * @return 默认的实例名
     */
    public static String getDefaultInstanceName(Class clazz) {
        if (clazz == null) {
            return null;
        }
        String className = clazz.getSimpleName();
        String firsrLowerChar = className.substring(0, 1).toLowerCase();
        className = firsrLowerChar + className.substring(1);
        return className;
    }
    
    
    

}


2, application.xml中注入

    
    

 

3, web.xml中配置监听

	
		org.springframework.web.context.ContextLoaderListener
	


 

 

 

 

你可能感兴趣的:(java)