實現BeanFactoryAware
public class ServiceLocator implements BeanFactoryAware {
private static BeanFactory beanFactory;@Overridepublic void setBeanFactory(BeanFactory beanFactory) throws BeansException {ServiceLocator.beanFactory = beanFactory;}/** * 根據提供的bean名稱得到相應的服務類 * * @param servName * bean名稱 */public static Object getService(String servName) {return beanFactory.getBean(servName);}}
spring配置文件
<bean id="serviceLocator" class="com.taobao.appcenter.common.ServiceLocator" lazy-init="false"/>
實現applicationContextAware
public class SpringContextsUtil implements ApplicationContextAware {private static ApplicationContext applicationContext; //Spring context @Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {SpringContextsUtil.applicationContext = applicationContext;}/** * @return ApplicationContext */ public static ApplicationContext getApplicationContext() { return applicationContext; } /** * 獲取對象 * @param name * @return Object 一個以所給名字注冊的bean的實例 * @throws BeansException */ public static Object getBean(String name) throws BeansException { return applicationContext.getBean(name); }}
spring xml配置文件
<bean id="springContext" class="com.taobao.appcenter.common.SpringContext" lazy-init="false"/>
通過servlet 或listener設置spring的ApplicationContext,以便后來引用,這個是針對web 工程的
public class SpringContext {private static ApplicationContext applicationContext; // Spring應用上下文環境public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException {SpringContext.applicationContext = applicationContext;}/** * @return ApplicationContext */public static ApplicationContext getApplicationContext() {return applicationContext;}public static Object getBean(String name) throws BeansException {return applicationContext.getBean(name);}}
上面的SpingContext誰沒實現任何接口的,不是回調的方式。而是在listener或者servlet中set進來
public class SpringContextLoaderListener extends ContextLoaderListener {public void contextInitialized(ServletContextEvent event){super.contextInitialized(event);SpringContext.setApplicationContext(WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()));}}
替換web.xml文件的listener為上面的文件
<listener><listener-class>com.taobao.appcenter.common.SpringContextLoaderListener</listener-class></listener>
servlet的代碼如下
public class SpringContextLoaderServlet extends ContextLoaderServlet { private ContextLoader contextLoader; public void init() throws ServletException { this.contextLoader = createContextLoader(); SpringContext.setApplicationContext(this.contextLoader.initWebApplicationContext(getServletContext())); }}
然后配置web.xml中的servlt和mapping即可。調用
由于使用的都是靜態函數,使用getBean(Stirng name)或者getService(String serviceName)就可以獲得xml配置的業務自己bean。
新聞熱點
疑難解答