spring bean 不使用注入的方式获取的两种方式
非注入方式取得spring注入bean的util类实现
第一种,我用在webservice接口中。
import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;/** * SpringBean的工具类<br> * 非注入方式取得spring注入bean的util类实现 * @author langkai * */public final class SpringBeanUtil implements ApplicationContextAware { private static ApplicationContext ctx; /** * 通过spring配置文件中配置的bean id取得bean对象 * @param id spring bean ID值 * @return spring bean对象 */ public static Object getBean(String id) { if (ctx == null) { throw new NullPointerException("ApplicationContext is null"); } return ctx.getBean(id); }@Overridepublic void setApplicationContext(ApplicationContext applicationcontext)throws BeansException {ctx = applicationcontext;}}
<bean name="code">ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("springConfig_bus.xml");IMsgBusService client = (IMsgBusService) context.getBean("client");