整合 spring

jersey2 官方还未正式支持 spring4, 但网上有好多支持方案,折腾了一圈后,还是用了 spring3;

pom 添加以下依赖配置

		<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
</dependency>
</dependencies>

添加 JerseyConfig 类

package com.easymylife.app.sys;

import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.spring.scope.RequestContextFilter; public class JerseyConfig extends ResourceConfig { public JerseyConfig() {
register(RequestContextFilter.class);
packages("com.easymylife.app.sys");
//register(LoggingFeature.class);
}
}

添加 SpringAnnotationConfig 类

package com.easymylife.app.sys;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; /**
* Spring configuration to include our services
*
*/
@Configuration
@ComponentScan(basePackageClasses = {})
public class SpringAnnotationConfig {
}

然后在 main 中调用

        final JerseyConfig resourceConfig = new JerseyConfig();
resourceConfig.property("contextConfig", new AnnotationConfigApplicationContext(SpringAnnotationConfig.class)); final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), resourceConfig, false);

就可以通过 @Autowired 注解进行注入

@Singleton
@Path("spring-resource")
@Service
public class SpringRequestResource { AtomicInteger counter = new AtomicInteger(); /* @Autowired
private GoodbyeService myGoodbyeService;*/ @Autowired
private ISaySthService saySthService; @GET
@Path("saysth")
@Produces(MediaType.TEXT_PLAIN)
public String getSaySth(){
return this.saySthService.hello("Grissom");
} @GET
@Path("users")
@Produces(MediaType.APPLICATION_JSON)
public List<SysUser> getUsers(){
return this.saySthService.getUsers();
} }

整合 hibernate

pom 配置


<!-- hibernate -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.0.Final</version>
</dependency>

如果通过 JPA 方式打开数据库 Session, 则在 main/resources/META-INF/ 下添加 persistence.xml 配置,

<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
<persistence-unit name="mysqlJPA" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.username" value="username" />
<property name="hibernate.connection.password" value="yourpwd" />
<property name="hibernate.connection.url" value="jdbc:mysql://www.yourdomain.cn:3306/dbname" />
<property name="hibernate.max_fetch_depth" value="3" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>

访问数据库代码

        EntityManagerFactory factory = Persistence.createEntityManagerFactory("mysqlJPA");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
Query query = em.createQuery("From SysUser");
List<SysUser> user = query.getResultList();

如果直接用 hibernate 创建 session, 则在 mian/resources 下添加 hibernate.cfg.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="hibernateSessionFactory">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">usernae</property>
<property name="hibernate.connection.password">pwd</property>
<property name="hibernate.connection.url">jdbc:mysql://www.yourdomain.cn:3306/dbname</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- <property name="hibernate.hbm2ddl.auto">create</property> -->
<mapping class="com.easymylife.app.sys.SysUser"/>
</session-factory>
</hibernate-configuration>

代码

        Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml"); sessionFactory = configuration.buildSessionFactory();
Session session = getInstance().sessionFactory.openSession();
Query query = session.createQuery("from SysUser");
List<SysUser> employees = query.list();
session.close();
return employees;

整合 log4j2

pom

		<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>

main/resources 下添加 log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>

<Configuration status="off" monitorInterval="1800">

    <properties>
<property name="LOG_HOME">C:\\logs</property>
<property name="ERROR_LOG_FILE_NAME">error</property>
<property name="INFO_LOG_FILE_NAME">info</property>
<property name="DEBUG_LOG_FILE_NAME">debug</property>
</properties> <Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d %-5p (%F:%L) - %m%n" />
</Console> <RollingRandomAccessFile name="ErrorLog"
fileName="${LOG_HOME}/${ERROR_LOG_FILE_NAME}.log"
filePattern="${LOG_HOME}/${ERROR_LOG_FILE_NAME}.log.%d{yyyy-MM-dd}.gz">
<PatternLayout
pattern="%d %-5p (%F:%L) - %m%n"/>
<Policies>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="100 MB"/>
</Policies>
<DefaultRolloverStrategy max="20"/>
</RollingRandomAccessFile>
<RollingRandomAccessFile name="InfoLog"
fileName="${LOG_HOME}/${INFO_LOG_FILE_NAME}.log"
filePattern="${LOG_HOME}/${INFO_LOG_FILE_NAME}.log.%d{yyyy-MM-dd}.gz">
<PatternLayout
pattern="%d %-5p (%F:%L) - %m%n"/>
<Policies>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="100 MB"/>
</Policies>
<DefaultRolloverStrategy max="20"/>
</RollingRandomAccessFile>
</Appenders> <Loggers>
<!-- 3rdparty Loggers -->
<logger name="org.springframework.core" level="info">
</logger>
<logger name="org.springframework.beans" level="info">
</logger>
<logger name="org.springframework.context" level="info">
</logger>
<logger name="org.springframework.web" level="info">
</logger>
<Logger name="org.hibernate" level="debug">
<appender-ref ref="InfoLog"/>
<appender-ref ref="Console"/>
</Logger>
<Logger name="org.hibernate.SQL" level="debug">
<appender-ref ref="InfoLog"/>
<appender-ref ref="Console"/>
</Logger> <logger name="com.easymylife.app.sys" level="error" includeLocation="true" additivity="false">
<appender-ref ref="ErrorLog"/>
<appender-ref ref="Console"/>
</logger>
<logger name="com.easymylife.app.sys" level="debug" includeLocation="true" additivity="false">
<appender-ref ref="InfoLog"/>
<appender-ref ref="Console"/>
</logger>
<root level="debug" includeLocation="true">
<appender-ref ref="Console"/>
</root>
</Loggers>
</Configuration>

我完整的 pom.xml

<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.easymylife.app</groupId>
<artifactId>sys</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>sys</name> <dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement> <dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-grizzly2-http</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.25.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.25.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.3.1</version>
</dependency> <!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
</dependency> <!-- hibernate -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.0.Final</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<inherited>true</inherited>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</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.easymylife.app.sys.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build> <properties>
<spring.version>4.3.1.RELEASE</spring.version>
<jersey.version>2.25.1</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

jersey2 整合 spring + hibernate + log4j2的更多相关文章

  1. eclipse环境下基于已构建struts2项目整合spring+hibernate

    本文是基于已构建的struts2项目基础上整合 spring+hibernate,若读者还不熟悉struts2项目,请先阅读 eclipse环境下基于tomcat-7.0.82构建struts2项目 ...

  2. 整合Spring+Hibernate+Struts2的时候发现json数据一直无法传到页面,提示no-Session

    执行了ajax,页面没有任何反应 怀疑json没有值,想查看json中的内容,使用了ObjectMapper: ObjectMapper om=new ObjectMapper(); System.o ...

  3. Struts2,Spring, Hibernate三大框架SSH的整合步骤

    整合步骤 创建web工程 引入相应的jar包 整合spring和hibernate框架 编写实体类pojo和hbm.xml文件 编写bean-base.xml文件 <!-- 1) 连接池实例 - ...

  4. Struts+Spring+Hibernate整合入门详解

    Java 5.0 Struts 2.0.9 Spring 2.0.6 Hibernate 3.2.4 作者:  Liu Liu 转载请注明出处 基本概念和典型实用例子. 一.基本概念       St ...

  5. SpringMVC+Spring+Hibernate+Maven+mysql整合

    一.准备工作 1.工具:jdk1.7.0_80(64)+tomcat7.0.68+myeclipse10.6+mysql-5.5.48-win322. 开发环境安装配置.Maven项目创建(参考:ht ...

  6. spring+hibernate+struts整合(1)

    spring+hibernate:整合 步骤1:引入类包 如下图:这里是所有的类包,为后面的struts整合考虑

  7. spring+hibernate+jpa+Druid的配置文件,spring整合Druid

    spring+hibernate+jpa+Druid的配置文件 spring+hibernate+jpa+Druid的完整配置 spring+hibernate+jpa+Druid的数据源配置 spr ...

  8. spring+hibernate整合:报错org.hibernate.HibernateException: No Session found for current thread

    spring+hibernate整合:报错信息如下 org.hibernate.HibernateException: No Session found for current thread at o ...

  9. Spring、Struts2+Spring+Hibernate整合步骤

    所使用的Jar包: Hibernate: Spring(使用MyEclipse自动导入框架功能) Struts2: 注解包和MySql驱动包: 1.配置Hibernate和Spring: <be ...

随机推荐

  1. 使用TaskScheduler 调度器 实现跨线程的控件访问

    //任务调度器 TaskScheduler UIscheduler = null; public Form1() { //获取任务调度器 UIscheduler = TaskScheduler.Fro ...

  2. 【工具推荐】截图工具 Snipaste

    0. 说明 [官网介绍] Snipaste 是一个简单但强大的截图工具,也可以让你将截图贴回到屏幕上!下载并打开 Snipaste,按下 F1 来开始截图,再按 F3,截图就在桌面置顶显示了.就这么简 ...

  3. Redis缓存穿透、缓存雪崩、redis并发问题分析

    把redis作为缓存使用已经是司空见惯,但是使用redis后也可能会碰到一系列的问题,尤其是数据量很大的时候,经典的几个问题如下: (一)缓存和数据库间数据一致性问题分布式环境下(单机就不用说了)非常 ...

  4. MySQL一个延迟案例

    突然接到报警显示MySQL主从之间延迟过大,随后尽快到集群上面看看,进行排查. 首先我们查看延迟是由什么造成的,排查一遍过后发现不是网卡和从库机器的负载,那就要从其他地方来排除了 查看binlog日志 ...

  5. JS内置对象-String对象、Date日期对象、Array数组对象、Math对象

    一.JavaScript中的所有事物都是对象:字符串.数组.数值.函数... 1.每个对象带有属性和方法 JavaScript允许自定义对象 2.自定义对象 a.定义并创建对象实例 b.使用函数来定义 ...

  6. 自带hyper -v 或者 Vmware安装Linux centos

    centos系统存在网盘,链接: https://pan.baidu.com/s/1A5ywyLjIegcftaT_xCvPbA 密码: n6v4 https://blog.csdn.net/nanc ...

  7. Swift 实践篇之链式 UI 代码

    https://blog.nswebfrog.com/2017/10/20/swift-practice-ui-chaining-code/

  8. HTTP协议请求方式: 中GET、POST和HEAD的介绍_孤帆一叶

    HTTP协议中GET.POST和HEAD的介绍 2008-05-10 14:15 GET: 请求指定的页面信息,并返回实体主体.HEAD: 只请求页面的首部.POST: 请求服务器接受所指定的文档作为 ...

  9. __init__函数

    初始化函数,类似于c++的构造函数 在创建一个对象时默认被调用,不需要手动调用.self后面接的形参,在类实例化的时候必须传递,__init__函数里的参数都属于成员变量

  10. 使用java实现hex和ascii码的转换

    几乎很少写JAVA代码,第一是确实不会,第二感觉JAVA写起来不爽(较python.golang),但总有万不得已必须要用java的时候.这里记录下使用java实现的hex十六进制和acsii码之间的 ...