Spring+Jetty+Jersey+Mybatis整合教程 无web.xml 、webapp版
原文链接 http://blog.csdn.net/whzhaochao/article/details/50152833
项目总体目录结构
项目结构说明
com.zhaochao.action 主要放处理RESTFull 接口业务,代码如下所示
@Path("user")
public class UserAction {
@Autowired
private UserService userService;
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public User getGreeting(@PathParam("id") Integer id) throws Exception {
return userService.getUserById(id);
}
}
com.zhaochao.bean 主要放数据表对应实体对象
public class User {
private Integer id;
private String name;
private Integer age;
private String password;
//省去getter setter 方法
}
对应数据库表脚本如下:
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`age` int(11) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', 'zhaochao', '20', 'zhaochao');
INSERT INTO `user` VALUES ('2', '赵云', '50', 'zhaoyun');
com.zhaochao.main 存放项目配置文件和主函数
ApplicationConfig jersey的配置文件
public class ApplicationConfig extends ResourceConfig {
public ApplicationConfig() {
packages("com.zhaochao.action");
register(JacksonFeature.class);
property(ServerProperties.METAINF_SERVICES_LOOKUP_DISABLE, true);
}
}
主要指明Jersey 的资源存放在com.zhaochao.action包下,以及将返回对象直接转换成JSON
SpringJavaConfiguration Spring的配置文件,相当于applicationcontext.xml
@Component
@Configuration
@ComponentScan(basePackages = {"com"})
public class SpringJavaConfiguration {
@Bean(autowire = Autowire.BY_TYPE)
public DataSource dataSource() {
PoolProperties poolProperties = new PoolProperties();
poolProperties.setDriverClassName("com.mysql.jdbc.Driver");
poolProperties.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false&maxReconnects=10");
poolProperties.setUsername("root");
poolProperties.setPassword("root");
poolProperties.setJmxEnabled(true);
poolProperties.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
poolProperties.setRemoveAbandonedTimeout(60);
poolProperties.setRemoveAbandoned(true);
poolProperties.setLogAbandoned(false);
poolProperties.setMinIdle(10);
poolProperties.setMinEvictableIdleTimeMillis(30000);
poolProperties.setMaxWait(10);
poolProperties.setInitialSize(2);
poolProperties.setMaxActive(10);
poolProperties.setTimeBetweenEvictionRunsMillis(30000);
poolProperties.setValidationQuery("SELECT 1");
poolProperties.setValidationInterval(30000);
poolProperties.setTestOnReturn(false);
poolProperties.setTestOnBorrow(true);
poolProperties.setTestWhileIdle(true);
poolProperties.setJmxEnabled(true);
DataSource dataSource = new DataSource();
dataSource.setPoolProperties(poolProperties);
return dataSource;
}
@Bean(name="sqlSessionFactory" )
public SqlSessionFactoryBean getSqlSesssionFactoryBean(){
SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
bean.setDataSource(dataSource());
Resource re =new ClassPathResource("mybatis-config.xml");
bean.setConfigLocation(re);
return bean;
}
@Bean(name="mapper",autowire=Autowire.BY_NAME)
public MapperScannerConfigurer getMapperScannerConfigurer(){
MapperScannerConfigurer conf=new MapperScannerConfigurer();
conf.setBasePackage("com.zhaochao.mapper");
conf.setSqlSessionFactoryBeanName("sqlSessionFactory");
return conf;
}
Main 项目启动主函数
public class Main {
public static void main(String[] args) throws Exception {
ApplicationConfig applicationConfig = new ApplicationConfig();
ServletHolder jerseyServlet = new ServletHolder(new ServletContainer(applicationConfig));
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
context.addServlet(jerseyServlet, "/rest/*");
context.addEventListener(new ContextLoaderListener());
context.addEventListener(new RequestContextListener());
context.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
context.setInitParameter("contextConfigLocation", SpringJavaConfiguration.class.getName());
int port=8080;
if(args.length==1){
port=Integer.parseInt(args[0]);
}
Server server = new Server(port);
server.setHandler(context);
try {
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
}
}
}
com.zhaochao.mapper Mybatis 接口
public interface UserMapper {
@Select("select * from user where id=#{id}")
public User getUserById(@Param("id") Integer id);
public User queryById(Integer id);
}
com.zhaochao.service user服务类
@Service("userService")
public class UserService {
@Autowired
private UserMapper mapper;
public UserMapper getMapper() {
return mapper;
}
public User getUserById(Integer userId){
//return mapper.getUserById(userId);
return mapper.queryById(userId);
}
}
src/main/resource 存放Mybatis配置文件
mybatis/user/UserMapper 这是UserMapper的映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhaochao.mapper.UserMapper">
<cache readOnly="true" eviction="FIFO" flushInterval="60000" />
<resultMap id="BaseResultMap" type="com.zhaochao.bean.User">
<result column="id" property="id" />
<result column="name" property="name" />
<result column="age" property="age" />
<result column="password" property="password" />
</resultMap>
<sql id="Base_Column_List">
id,name,age,password
</sql>
<select id="queryById" resultMap="BaseResultMap" parameterType="Object" useCache="true">
select
<include refid="Base_Column_List" />
from user where id = #{id}
</select>
</mapper>
mybatis-config.xml mybatis 配置文件
<?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">
<configuration>
<settings>
<setting name="cacheEnabled" value="true" />
</settings>
<mappers>
<mapper resource="mybatis/user/UserMapper.xml" />
</mappers>
</configuration>
log4j.xml log4j配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<!-- 开发时输出控制台 上线后取消-->
<appender name="LOG.CONSOLE" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d - %c -%-4r [%t] %-5p %x - %m%n" />
</layout>
<!--限制输出级别 -->
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMax" value="ERROR" />
<param name="LevelMin" value="TRACE" />
</filter>
</appender>
<!--将级别为DEBUG的信息输出到控制台 -->
<appender name="LOG.DEBUG" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="/zhaochao/jersey/debug.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %p [%c] - %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="DEBUG" />
<param name="LevelMax" value="DEBUG" />
</filter>
</appender>
<!--将级别为INFO的信息输出到控制台 -->
<appender name="LOG.INFO" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="/zhaochao/jersey/info.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %p [%c] - %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="INFO" />
<param name="LevelMax" value="INFO" />
</filter>
</appender>
<!--将级别为WARN的信息输出到控制台 -->
<appender name="LOG.WARN" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="/zhaochao/jersey/warn.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %p [%c] - %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="WARN" />
<param name="LevelMax" value="WARN" />
</filter>
</appender>
<!--将级别为ERROR的信息输出到控制台 -->
<appender name="LOG.ERROR" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="/zhaochao/jersey/error.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %p [%c] - %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="ERROR" />
<param name="LevelMax" value="ERROR" />
</filter>
</appender>
<!--将级别为FATAL的信息输出到日志 -->
<appender name="LOG.FATAL" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="/zhaochao/jersey/fatal.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %p [%c] - %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="FATAL" />
<param name="LevelMax" value="FATAL" />
</filter>
</appender>
<root>
<priority value="INFO" />
<appender-ref ref="LOG.DEBUG" />
<appender-ref ref="LOG.INFO" />
<appender-ref ref="LOG.WARN" />
<appender-ref ref="LOG.ERROR" />
<appender-ref ref="LOG.FATAL" />
<!-- -->
<appender-ref ref="LOG.CONSOLE" />
</root>
</log4j:configuration>
pom.xml maven 项目配置文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.underdog.jersey</groupId>
<artifactId>jersey-spring-jetty</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.17</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
<version>2.17</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlets</artifactId>
<version>9.2.6.v20141205</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>9.2.6.v20141205</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.17</version>
</dependency>
<!-- tomcat jdbc pool -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
<version>8.0.28</version>
</dependency>
<!-- Mybatis 开发包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.1.1</version>
</dependency>
<!-- Mybatis 和Spring的 整合包,是mybatis出的 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.1.1</version>
</dependency>
<!-- mysql的数据库驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<!-- 阿里巴巴fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
<!-- 日志打印 log4j包 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.2</version>
<configuration>
<createDependencyReducedPom>true</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.zhaochao.main.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.zhaochao.main.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
运行项目
- eclipse 直接在Main.java中run as java application
- 用maven 打开jar包后,在项目的target 目录中找到jersey-spring-jetty-1.0-SNAPSHOT.jar通过以下命令启动项目
java -jar jersey-spring-jetty-1.0-SNAPSHOT.jar
测试项目
打开浏览器输入http://localhost:8080/rest/user/1
完整项目地址:https://github.com/whzhaochao/spring-jetty-jersey-mybatis