Gradle+SpringBoot+SpringMVC+Mybatis+Jersey+Mybatis+MySQL项目整合实例(全注解实例)

一.项目摘要:

1.进入https://start.spring.io网站下载实例模板(当前组合模板为:gradle+SpringBoot+Jersey)

2.完整项目如图显示:

Gradle+SpringBoot+SpringMVC+Mybatis+Jersey+Mybatis+MySQL项目整合实例(全注解实例)_第1张图片

二.项目具体实施:

1.安装Gradle插件,官网为:https://gradle.org/(这里是5.6.2)

2.Eclipse中安装Gradle插件。(新的Eclipse一般会有这个插件,先可以检查一下是否已经有。)

这里项目名为:helper。

3.修改maven仓库,项目中用笔记本打开build.gradle,将仓库地址修改如下:

repositories {

     mavenLocal()

    maven{ url 'http://maven.aliyun.com/nexus/content/groups/public/'}

    mavenCentral()

}

4.导入模板项目,则项目开始初始化,可能需要一段时间。

5.找到HelperApplication.java
  运行该类,这时候浏览器输入localhost:8080/
  浏览器报错,这是因为我们没有写任何controller。

6.springBoot和jersey整合:

(1)创建如下包:

  com.helper.app

  com.helper.entity

  com.helper.mapper

  com.helper.service

  com.helper.service.impl

  com.helper.resource

  com.helper.utils

将模板中的ServletInitializer.java和HelperApplication.java移入com.helper.app

(2)注册servlet组件:

 在com.helper.app包下创建如下类并编写如下代码:

package com.helper.app;

 

import org.glassfish.jersey.servlet.ServletContainer;

import org.glassfish.jersey.servlet.ServletProperties;

import org.springframework.boot.SpringBootConfiguration;

import org.springframework.boot.web.servlet.ServletRegistrationBean;

import org.springframework.context.annotation.Bean;

@SpringBootConfiguration

public class ServletRegistration {

   // 注册Servlet组件

   @Bean

   public ServletRegistrationBean jerseyServlet() {

      ServletRegistrationBean registration=new ServletRegistrationBean(new ServletContainer(),"/helper/*");

   registration.addInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS,JerseyConfig.class.getName());

      return registration;

   }

 

}

(3)JerseyConfig:

package com.helper.app;

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.helper.resource");

   }

}

(4)编写UserResource.java

package com.helper.resource;

 

import java.util.List;

 

import javax.ws.rs.GET;

import javax.ws.rs.Path;

import javax.ws.rs.Produces;

import javax.ws.rs.core.MediaType;

 

import org.springframework.beans.factory.annotation.Autowired;

 

import com.helper.entity.User;

import com.helper.service.UserService;

 

@Path("user")

public class UserResource {

   @GET

   @Produces(MediaType.APPLICATION_JSON)

   public String getUser() {

      return hello;

   }

}

(5)这时候,重新启动springBoot实例,浏览器输入:localhost:8080/helper/user

浏览器如果输出:“hello”,则springBoot与Jersey整合成功。

7.springBoot与Mybatis整合:

(1)在mysql创建数据库helper并创建一张user表,如下代码:

CREATE TABLE `user` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `name` varchar(255) DEFAULT NULL,

  `age` int(11) DEFAULT NULL,

  `job` varchar(255) DEFAULT NULL,

  `telphone` varchar(255) DEFAULT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

 

INSERT INTO `user` VALUES ('1', 'www', '23', '4', '23');

(2)创建实体类User.java

  package com.helper.entity;

 

public class User {

   private int id;

   private String name;

   private int age;

   private String job;

   private String telphone;

   public int getId() {

      return id;

   }

   public void setId(int id) {

      this.id = id;

   }

   public String getName() {

      return name;

   }

   public void setName(String name) {

      this.name = name;

   }

   public int getAge() {

      return age;

   }

   public void setAge(int age) {

      this.age = age;

   }

   public String getJob() {

      return job;

   }

   public void setJob(String job) {

      this.job = job;

   }

   public String getTelphone() {

      return telphone;

   }

   public void setTelphone(String telphone) {

      this.telphone = telphone;

   }

}

(3)在application.properties中添加如下代码:

spring.datasource.driverClassName = com.mysql.jdbc.Driver

spring.datasource.url = jdbc:mysql://127.0.0.1:3306/helper?useUnicode=true&characterEncoding=UTF-8

spring.datasource.username = root

spring.datasource.password = 

spring.datasource.initialPoolSize=5  

spring.datasource.maxIdleTime=60  

spring.datasource.maxPoolSize=15

spring.datasource.autoCommitOnClose=false

这里根据自己的mysql修改用户名和密码

(4)在build.gradle中添加mybatis和c3p0相关依赖,

build.gradle完整文件如下:

plugins {

   id 'org.springframework.boot' version '2.2.0.RELEASE'

   id 'io.spring.dependency-management' version '1.0.8.RELEASE'

   id 'java'

   id 'war'

}       

 

group = 'com.helper'

version = '0.0.1-SNAPSHOT'

sourceCompatibility = '1.8'

 

repositories {

     mavenLocal()

    maven{ url 'http://maven.aliyun.com/nexus/content/groups/public/'}

    mavenCentral()

}

 

dependencies {

   implementation 'org.springframework.boot:spring-boot-starter-jersey'

   implementation 'org.springframework.boot:spring-boot-starter-web'

   providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'

   testImplementation('org.springframework.boot:spring-boot-starter-test') {

      exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'

   }

    compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.0")

    testCompile('org.mybatis.spring.boot:mybatis-spring-boot-starter-test:1.3.0')

   compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.16'

   compile group: 'com.mchange', name: 'c3p0', version: '0.9.5.4' 

}

 

test {

   useJUnitPlatform()

}

(5)添加mybatis数据源,创建DataSourceConfiguration类,添加如下代码:

 package com.helper.app;

import java.beans.PropertyVetoException;

import javax.sql.DataSource;

import org.mybatis.spring.annotation.MapperScan;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.boot.SpringBootConfiguration;

import org.springframework.context.annotation.Bean;

import com.mchange.v2.c3p0.ComboPooledDataSource;

 

@MapperScan("com.helper.mapper")

@SpringBootConfiguration

// @PropertySource({"classpath:application.properties"})

public class DataSourceConfiguration {

   @Value("${spring.datasource.driverClassName}")

   private String driver;

   @Value("${spring.datasource.url}")

   private String url;

   @Value("${spring.datasource.username}")

   private String username;

   @Value("${spring.datasource.password}")

   private String password;

   @Value("${spring.datasource.initialPoolSize}")

   private int initialPoolSize;

   @Value("${spring.datasource.maxIdleTime}")

   private int maxIdleTime;

   @Value("${spring.datasource.maxPoolSize}")

   private int maxPoolSize;

   @Value("${spring.datasource.autoCommitOnClose}")

   private boolean autoCommitOnClose;

   @Bean

   public DataSource createDataSource() throws PropertyVetoException {

      ComboPooledDataSource dataSource=new ComboPooledDataSource();

      dataSource.setDriverClass(driver);

      dataSource.setJdbcUrl(url);

      dataSource.setUser(username);

      dataSource.setPassword(password);

      dataSource.setInitialPoolSize(initialPoolSize);

      dataSource.setMaxIdleTime(maxIdleTime);

      dataSource.setMaxPoolSize(maxPoolSize);

      dataSource.setAutoCommitOnClose(autoCommitOnClose);

      dataSource.setAutoCommitOnClose(false);

      return dataSource;

   }

}

(6)在com.helper.mapper中创建UserMapper.java:

package com.helper.mapper;

 

import java.util.List;

 

import org.apache.ibatis.annotations.Select;

import org.springframework.stereotype.Component;

import com.helper.entity.User;

 

@Component

public interface UserMapper {

   @Select("select * from user")

   public List findUsers();

}

(7)创建Service接口之前,我们需要创建mybatis事务类,因为需要支持事务。于是,在com.helper.app中创建TransactionManagementConfiguration类,完整内容如下:

package com.helper.app;

 

import javax.sql.DataSource;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.SpringBootConfiguration;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import org.springframework.transaction.TransactionManager;

import org.springframework.transaction.annotation.EnableTransactionManagement;

import org.springframework.transaction.annotation.TransactionManagementConfigurer;

 

@SpringBootConfiguration

@EnableTransactionManagement

public class TransactionManagementConfiguration implements TransactionManagementConfigurer {

   @Autowired

   private DataSource dataSource;

 

   @Override

   public TransactionManager annotationDrivenTransactionManager() {

      // TODO Auto-generated method stub

      return new DataSourceTransactionManager(dataSource);

   }

 

}

(8)创建业务接口,在com.helper.service中创建如下接口:

package com.helper.service;

 

import java.util.List;

 

import org.springframework.transaction.annotation.Transactional;

 

import com.helper.entity.User;

@Transactional

public interface UserService {

   public List getUsers();

}

(9)实现该接口,在com.helper.service.impl中编写如下类:

package com.helper.service.impl;

 

import java.util.List;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

 

import com.helper.entity.User;

import com.helper.mapper.UserMapper;

import com.helper.service.UserService;

 

@Service

public class UserServiceImpl implements UserService  {

   @Autowired

   private UserMapper userMapper;

   @Override

   public List getUsers() {

      // TODO Auto-generated method stub

      return userMapper.findUsers();

   }

 

}

(10)在com.helper.app创建ServiceBeans类:

package com.helper.app;

 

import org.springframework.boot.SpringBootConfiguration;

import org.springframework.context.annotation.Bean;

 

import com.helper.service.UserService;

import com.helper.service.impl.UserServiceImpl;

 

@SpringBootConfiguration

public class ServiceBeans {

   @Bean

   public UserService getUserService() {

      return new UserServiceImpl();

   }

}

(11)将UserResource类修改如下:

package com.helper.resource;

 

import java.util.List;

 

import javax.ws.rs.GET;

import javax.ws.rs.Path;

import javax.ws.rs.Produces;

import javax.ws.rs.core.MediaType;

 

import org.springframework.beans.factory.annotation.Autowired;

 

import com.helper.entity.User;

import com.helper.service.UserService;

 

@Path("user")

public class UserResource {

   @Autowired

   private UserService userService;

   @GET

   @Produces(MediaType.APPLICATION_JSON)

   public List getUsers() {

      return userService.getUsers();

   }

}

再次启动HelperApplication,浏览器输入localhost:8080/helper/user,如果浏览器输出所用用户的json信息,则说明该项目整合完成。
8.修改8080端口:

  在application.properties文件中添加如下内容:

  server.port=80,则端口修改完成。

9.有时候,我们要进行测试类的编写,

  (1)添加依赖:

 testCompile group: 'org.junit.platform', name: 'junit-platform-launcher', version: '1.1.1'

在src/test/java中创建如下包:

com.helper.test.mapper

com.helper.test.service

(2)UserMapperTest.java:

package com.helper.test.mapper;

import java.util.List;

 

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

 

import com.helper.app.HelperApplication;

import com.helper.entity.User;

import com.helper.mapper.UserMapper;

 

@RunWith(SpringJUnit4ClassRunner.class)

@SpringBootTest(classes=HelperApplication.class)

public class UserMapperTest {

   @Autowired

   private UserMapper userMapper;

   @Test

   public void test1() {

      List users = userMapper.findUsers();

      System.out.println(users);

   }

}

(3)UserServiceTest.java:

package com.helper.test.service;

import java.util.List;

 

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

 

import com.helper.app.HelperApplication;

import com.helper.entity.User;

import com.helper.service.UserService;

 

@RunWith(SpringJUnit4ClassRunner.class)

@SpringBootTest(classes=HelperApplication.class)

public class UserServiceTest {

   @Autowired

   private UserService userService;

   @Test

   public void test1() {

      List users = userService.getUsers();

      System.out.println(users);

   }

}

在这里,controller层测试还没有编写。Controller可以启动项目后利用浏览器插件做为测试工具。

资源下载地址(包含源码和word文件,word文件和此文章一致):https://download.csdn.net/download/qq_25337221/11887735

三.参考链接:

(无)

本内容由安康学院“雨季”原创。

你可能感兴趣的:(spring,Jersey,mybatis)