Jetty - 在整合Spring的J2SE應用程式中嵌入Jetty的Web功能(Web中獲取Spring上下文中的Bean)

襲冷發表於2018-02-28

一、說明

    如果開發了一個J2SE的應用程式,然後想用Web來完成一些的使用者介面,但是在啟動 Jetty 之前就已經建立和使用了 Spring 的 ApplicationContext,但這些Web的業務中也要依賴於 Spring 的 ApplicationContext,這樣就會遇到一個問題:原有應用程式和新加Web不在同一個上下文,在Web中如何獲取Spring中管理的Bean呢?


二、建立jetty-context.xml,並在原有的spring中引入

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    	http://www.springframework.org/schema/beans/spring-beans.xsd"> 

	<bean id="handler" class="org.eclipse.jetty.webapp.WebAppContext">
		<property name="contextPath" value="/admin" />
		<property name="resourceBase" value="./webapps/admin" />
		<property name="logUrlOnStart" value="true" />
		<property name="configurationDiscovered" value="true" />
	</bean>
	
	<bean id="server" class="org.eclipse.jetty.server.Server" init-method="start" destroy-method="stop">
		<property name="connectors">
			<list>
				<bean id="Connector" class="org.eclipse.jetty.server.nio.SelectChannelConnector">
					<property name="port" value="8080" />
				</bean>
			</list>
		</property>
		<property name="handler">
			<ref bean="handler" />
		</property>
	</bean>  
</beans>
二、專案中新增web目錄,並在該目錄下完善這個web的jsp或servlet

     |--webapps
        |--admin

           |--WEB-INF
              |--web.xml
           |--index.jsp


三、建立一個獲取spring管理的bean的工具類(完成上兩步之後,問題來了,在這個web中管理的servlet和原有的Spring中管理的Bean是不同的上下文,不能直接注入

package com.xilen.util.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 通過實現ApplicationContextAware以獲得這個Spring配置所在的上下文
 */
public class ApplicationContextHelper implements ApplicationContextAware {

	private static ApplicationContext applicationContext = null;

	/**
	 * 獲得Bean物件
	 */
	public static <T> T getBean(Class<T> clazz) {
		return applicationContext.getBean(clazz);
	}

	/**
	 * 獲得Bean物件
	 */
	public static Object getBean(String className) {
		return applicationContext.getBean(className);
	}

	/**
	 * 獲得應用所在上下文環境
	 */
	public static ApplicationContext getContext() {
		return applicationContext;
	}

	/**
	 * 以讓 spring 把 application context 設定進來
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		ApplicationContextHelper.applicationContext = applicationContext;
	}

}
四、把ApplicationContextHelper配置到應用程式的Spring環境中去
<bean id="applicationContextHelper" class="com.xilen.util.spring.ApplicationContextHelper" />
五、最後,在web的servlet中獲取並使用應用程式中Spring管理的Bean
UserInfoService userInfoService = (UserInfoService) ApplicationContextHelper.getBean("userInfoService"); 
六、參考

    http://virusfu.iteye.com/blog/1220407



相關文章