Spring普通类获取bean

1.编写工具类如下:

package com.jeecms.common.util;

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

/**
* 通过该类即可在普通工具类里获取spring管理的bean 
* 
*/  
@Component
public class SpringTool implements ApplicationContextAware {  
     private static ApplicationContext applicationContext;  
     
        @Override  
        public void setApplicationContext(ApplicationContext context)  
            throws BeansException {  
            SpringTool.applicationContext = context;  
        }  
        public static Object getBean(String name){  
            return applicationContext.getBean(name);  
        }   
       
} 

记得类名加上@Component标签,告诉Spring管理这个对象

2.Spring文件加上如下配置

<bean id="springTool" class="com.jeecms.common.util.SpringTool" lazy-init="false"/>

3.调用工具类获取bean

CmsUserMng cmsUserMng=(CmsUserMng)SpringTool.getBean("cmsUserMng");

 

posted @ 2018-05-09 13:55  Againn  阅读(2034)  评论(0编辑  收藏  举报