spring管理的类如何调用非spring管理的类.
就是使用一个spring提供的感知概念,在容器启动的时候,注入上下文即可.
下面是一个工具类.
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component; /**
* spring上下文的持有者:
* ApplicationContextAware 可感知ApplicationContex,
* 只要实现了该接口的类,交给Spring管理后,Spring就能感知到,
* 感知后就会调用setApplicationContext注入当前容器的上下文.
* @author lne
*/
@Component
public class SpringApplicationContextHolder implements ApplicationContextAware { // 使用一个变量接受ApplicationContext
private static ApplicationContext ctx = null; @Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
System.out.println(ctx);
SpringApplicationContextHolder.ctx = ctx;
} public static Object getBean(String name) { return ctx.getBean(name);
} public static Object getBean(Class clazz) { return ctx.getBean(clazz);
}
}