非spring托管类获取bean

来源:互联网 发布:快速提高英语口语 知乎 编辑:程序博客网 时间:2024/06/05 04:19
  • 方式一:实现ApplicationContextAware接口

同时还要把实现该接口的bean放入spring容器中

/*applicationContext.xml*/<bean class="com.tortuousroad.framework.base.context.SpringApplicationContext"/>

spring会自动监测实现了ApplicationContextAware的类,
并注入ApplicationContext

public class SpringApplicationContext implements ApplicationContextAware{    public SpringApplicationContext() {        System.out.println("context constructor");    }    /**     * !此bean一定要手动放入容器中!     */    private static ApplicationContext context;    public static <T> T getBean(String beanId){        return (T)context.getBean(beanId);    }    public static <T> T getBean(Class<T> clazz){        return context.getBean(clazz);    }    @Override    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {        SpringApplicationContext.context=applicationContext;    }}
  • 方式二
public class SpringBeanFactory {    public static Object getBean(String[] paths, String name){        XmlWebApplicationContext ctx = new XmlWebApplicationContext();        ctx.setConfigLocations(paths);        ctx.setServletContext(new MockServletContext(""));        ctx.refresh();        return ctx.getBean(name);    }    public static Object getBean(String name){        String[] paths = { "applicationContext.xml" };        return getBean(paths,name);    }}
原创粉丝点击