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");

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM