整合 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. [PC]可用于Windows Server 2008 R2的Xbox One手柄、接收器驱动

    让客厅里的Gen8可以玩FC和PS1游戏,折腾了半天,终于将Xbox One手柄驱动弄好: http://www.drvsky.com/Microsoft/Xbox_One.htm http://ww ...

  2. MySQL基础之 支持的数据类型

    MySQL的数值类型 整数类型 字节 有符号 无符号 TINYINT 1 -128~+127 0~255 SAMLLINT 2 -32768~+32767 0~65535 MEDIUMINT 3 -8 ...

  3. 阿里八八Alpha阶段Scrum(6/12)

    今日进度 叶文滔: 修复了无法正确判断拖曳与点击的BUG,并且成功连接添加界面. 会议内容 会议照片 明日安排 叶文滔: 继续完善按钮功能 王国超: 继续攻克日程界面显示存在的BUG 俞鋆: 继续进行 ...

  4. 张高兴的 .NET Core IoT 入门指南:(二)GPIO 的使用

    什么是 GPIO GPIO 是 General Purpose Input Output 的缩写,即"通用输入输出". Raspberry Pi 有两行 GPIO 引脚, Rasp ...

  5. PHP常用算法和数据结构示例

    <?php header("content-type:text/html;charset=utf-8"); $arr=array(3,5,8,4,9,6,1,7,2); ec ...

  6. json 压缩中文不转码

    $testJSON=array('name'=>'中文字符串','value'=>'test'); echo json_encode($testJSON, JSON_UNESCAPED_U ...

  7. snmpwalk,iptables

    -A RH-Firewall-1-INPUT -i lo -j ACCEPT -A INPUT -s 1.1.1.1 -p udp -d 2.2.2.2 --dport 161 -j ACCEPT - ...

  8. IDEA导包(以junit为例)

    ## IDEA导包(以junit为例) 1. 准备junit的jar包: * hamcrest-core-1.3.jar * junit-4.12.jar 2. 在项目中新建文件夹:lib 3. 将j ...

  9. C++之构造函数拷贝

    拷贝构造函数,顾名思义,就是通过拷贝对象的方式创建一个新对象.拷贝构造函数有两种原型(我们继续以book类来说明拷贝构造函数原型): book(book &b); book(const boo ...

  10. 警惕ASP.NET MVC中的ValidateInputAttribute

    最近在做一个ASP.NET MVC项目的时候发现,有一个Controller的Action死活都没法接收到从客户端提交过来的Html表单请求和数据,后来才发现是因为默认情况下ASP.NET MVC在执 ...