restlet2.0.6+spring3.2.2+mybatis3.2.3 集成

基于上一篇博客http://wuxiangqian.iteye.com/blog/1987841, 接口完成后,项目进度也跟上了,那就得把架构完善完善。让spring来管理restlet及mybatis。结果折腾好几天,终于功夫不负有心人,大功告成!

第一步:配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<display-name>RestService</display-name>

  	
	<servlet>  
		<servlet-name>RestletServlet</servlet-name>  
		<servlet-class>org.restlet.ext.spring.SpringServerServlet</servlet-class>  
		<init-param>  
			<param-name>org.restlet.component</param-name>  
			<param-value>component</param-value>  
		</init-param>  
	</servlet>   

    <servlet-mapping>
      <servlet-name>RestletServlet</servlet-name>  
      <url-pattern>/*</url-pattern>  
    </servlet-mapping> 
    
    
    
	
	
	<!-- spring的监听以及配置文件加载信息 -->
	<context-param>
    <param-name>contextConfigLocation</param-name>
    	 <!-- 上面配置的spring配置文件的路径,区分大小写 -->
 	  <param-value>WEB-INF/ApplicationContext.xml</param-value>
    </context-param>
 	<listener>
  		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	
   <welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
</web-app>

  

第二步:在WEB-INF文件夹下新建ApplicationContext.xml

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

<!--	<aop:aspectj-autoproxy/> -->
<!--	<aop:aspectj-autoproxy proxy-target-class="true"/>-->
   	<bean id="component" class="org.restlet.ext.spring.SpringComponent">
		<property name="defaultTarget" ref="restRoute" />
	</bean>
	<bean id="restRoute" class="org.restlet.ext.spring.SpringRouter">
		<property name="attachments" >
			<map>
				<entry key="/ws/user/login">
					<bean class="org.restlet.ext.spring.SpringFinder">
						<lookup-method name="create" bean="userLoginResource" />
					</bean>
				</entry>
			</map>
		</property>

	</bean>
	<!-- 用户登录资源文件 -->
	<bean id="userLoginResource" class="com.opro.ims.i.restservice.resource.UserLoginResource" scope="prototype">
	</bean>
	
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" 
			destroy-method="close">
		<property name="driverClass" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
		<property name="jdbcUrl" value="jdbc:sqlserver://192.168.1.22:1433; DatabaseName=DBNAME" />
		<property name="user" value="" />
		<property name="password" value="" />
		<!-- 初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
		<property name="initialPoolSize" value="1"/>
		<!-- 连接池中保留的最小连接数。 -->
		<property name="minPoolSize" value="1"/> 
		<!-- 连接池中保留的最大连接数。Default: 15 -->
		<property name="maxPoolSize" value="300"/>
		<!-- 最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
		<property name="maxIdleTime" value="60"/> 
		<!-- 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
		<property name="acquireIncrement" value="5"/> 
		<!-- 每60秒检查所有连接池中的空闲连接。Default: 0 -->
		<property name="idleConnectionTestPeriod" value="60"/>
	</bean>

	<!--把mybatis SqlSessionFactory的创建交由spring管理-->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" /><!--数据源-->
<!--		<property name="mapperLocations" value="classpath:com//*Mapper.xml" />-->
		<property name="configLocation" value="classpath:com/mybatis/config/Configuration.xml" /><!--mybatis配置文件路径-->
	</bean>
	
	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="sqlSessionFactory" />
	</bean>
	
	<bean id="baseDao" class="com.opro.ims.i.restservice.core.impl.BaseDaoImpl">
		<property name="sqlSession" ref="sqlSession" />
	</bean>

	<!-- scan for mappers and let them be autowired -->
<!--	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">-->
<!--		<property name="basePackage" value="com.opro.ims.i.restservice.bean" />-根据自己的项目路径配置-->
<!--	</bean>-->

	<!--把mybatis的事务交由spring去管理-->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" /><!--注意:此处的数据源要与sqlSessionFactory中的dataSource相同-->
	</bean>
    
    <!-- 注入 ApplicationContext  暂时未使用 -->
<!--    <bean id="springfactory" class="com.opro.ims.i.restservice.utils.SpringFactoryUtil"></bean>-->
    
    
    <!-- 自动扫描注解注入 -->
<!--	<context:annotation-config />-->
    <context:component-scan base-package="com.opro.ims.i.restservice">

    </context:component-scan>
    
	<!--启用spring @Transactional注解  不加上proxy-target-class = ture 不能依赖注入-->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
</beans>

第三步:修改Mybatis配置文件,关于连接数据库这块都交给spring管理了,所以得去掉数据库连接的代码

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-config.dtd">

<!-- 注意:每个标签必须按顺序写,不然蛋疼的DTD会提示错误:The content of element type "configuration" must match "(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,plugins?,environments?,mappers?)". -->
<configuration>
	
	<!-- 设置缓存和延迟加载等等重要的运行时的行为方式 -->
	<settings>
		<!-- 设置超时时间,它决定驱动等待一个数据库响应的时间  -->
		<setting name="defaultStatementTimeout" value="25000"/>
		<!-- 这个配置使全局的映射器启用或禁用缓存  -->
		<setting name="cacheEnabled" value="true"/>
		
		<!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载  -->
<!-- 		<setting name="lazyLoadingEnabled" value="true"/> -->
		<!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载  -->
		<setting name="aggressiveLazyLoading" value="true"/>
		
		<!-- 允许或不允许多种结果集从一个单独的语句中返回(需要适合的驱动)  -->
		<setting name="multipleResultSetsEnabled" value="true"/>
		<!-- 使用列标签代替列名。不同的驱动在这方便表现不同。参考驱动文档或充分测试两种方法来决定所使用的驱动  -->
		<setting name="useColumnLabel" value="true"/>
		<!-- 允许JDBC支持生成的键。需要适合的驱动。如果设置为true则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如Derby)  -->
		<setting name="useGeneratedKeys" value="false"/>
		<!-- 指定MyBatis如何自动映射列到字段/属性。PARTIAL只会自动映射简单,没有嵌套的结果。FULL会自动映射任意复杂的结果(嵌套的或其他情况)  -->
		<setting name="autoMappingBehavior" value="PARTIAL"/>
		<!-- 配置默认的执行器。SIMPLE执行器没有什么特别之处。REUSE执行器重用预处理语句。BATCH执行器重用语句和批量更新  -->
		<setting name="defaultExecutorType" value="SIMPLE"/>
	</settings>
	
	<!-- 别名 -->
	<typeAliases>
		<!-- 用户bean-用户登录时映射使用  -->
		<typeAlias alias="UserBean" type="com.restservice.bean.UserBean"/>
	
	
	<!-- ORM映射文件 -->
	<mappers>
		<!-- 用户测试XML -->
		<mapper resource="com/restservice/bean/UserBean.xml" />
	</mappers>	
</configuration> 

第四步:使用spring依赖注入,在resource,service,dao层中加上对应的注解,例如:

//resource   

//@Path("ws/user/login")
@Controller
@Scope("prototype")
public class UserLoginResource extends BestResource {

	@Resource
	private UserLoginService userLoginService;
}

 把//@Path("ws/user/login")注释了,由spring管理了,这个就没用了

第五步:可以把ApplicationContext.xml拷贝到Src下写个测试类是否成功

package test.ws.client;

import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.type.TypeException;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.opro.ims.i.restservice.service.UserLoginService;

public class SpringTest {
	//加载ApplicationContext.xml文件
	private ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

	// 测试SessionFactory
	@Test
	public void testSessionFactory() {
		UserLoginService sessionFactory = (UserLoginService) ac.getBean("userLoginService");
		System.out.println("-------> " + sessionFactory);
	}

	// 测试事务管理
	@Test
	public void testTransaction() {
		UserLoginService testService = (UserLoginService) ac.getBean("userLoginService");
		try {
			System.out.println(testService.findUser("xqwu"));
		} catch (TypeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

第六步:如果测试成功了,那就启动服务吧,希望一次性成功!

猜你喜欢

转载自wuxiangqian.iteye.com/blog/1996666