非Controller中调用Service

 1.       新增文件

package com.library.common;

 

import org.springframework.beans.BeansException;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ApplicationContextAware;

 

public class ApplicationContextHelper implements ApplicationContextAware {

        

    private static ApplicationContext appCtx;

 

    @Override

    public void setApplicationContext( ApplicationContext applicationContext ) throws BeansException {

        appCtx = applicationContext;

    }

 

    public static Object getBean( String beanName ) {

        return appCtx.getBean( beanName );

    }

   

    public static <T> T getBean(Class<T> clz) {

        return (T)appCtx.getBean(clz);

    }

}

 

 

2.       spring.xml中的最后加入

<bean id="SpringApplicationContext" class="com.library.common.ApplicationContextHelper"></bean>

 

3.       调用代码

UserService us=ApplicationContextHelper.getBean(UserService.class);

posted @ 2014-04-25 10:45  wang_tale  阅读(2173)  评论(1编辑  收藏  举报