博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Gradle + IDEA 搭建一个 Spring + SpringMVC + Mybatis 的极速后台开发框架
阅读量:6030 次
发布时间:2019-06-20

本文共 8353 字,大约阅读时间需要 27 分钟。

hot3.png

一、创建项目

Create New Project

    -> Gradle -> Java & Web

    -> GroupId & ArtifactId

    -> Create sparete module per source set & Use local gradle distribution

    -> select “Gradle home”

    -> Next

    -> Finish

 

二、搭建项目结构

项目结构如下:

其中:

config: 保存 Spring 的一些配置

controller: Controller

dao: DAO

model: Model

service: Service

utils: Servlet 配置

 

没有web.xml。

 

三、完善项目

 

四、各文件内容

SpringCoreConfig.java

package com.haier.demo.config;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;@Configuration@ComponentScan({ "com.haier.demo.service" })public class SpringCoreConfig {}

该文件用以代替spring-core-config.xml

 

SpringWebConfig.java

package com.haier.demo.config;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.tomcat.dbcp.dbcp.BasicDataSource;import org.mybatis.spring.SqlSessionFactoryBean;import org.mybatis.spring.mapper.MapperScannerConfigurer;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.EnableWebMvc;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import org.springframework.web.servlet.view.InternalResourceViewResolver;import org.springframework.web.servlet.view.JstlView;@EnableWebMvc@Configuration@ComponentScan({ "com.haier.demo.controller" })public class SpringWebConfig extends WebMvcConfigurerAdapter {   @Override   public void addResourceHandlers(ResourceHandlerRegistry registry) {       registry.addResourceHandler("/resources/**")               .addResourceLocations("/resources/");   }   @Bean   public InternalResourceViewResolver viewResolver() {       InternalResourceViewResolver viewResolver               = new InternalResourceViewResolver();       viewResolver.setViewClass(JstlView.class);       viewResolver.setPrefix("/WEB-INF/views/jsp/");       viewResolver.setSuffix(".jsp");       return viewResolver;   }   @Bean   public BasicDataSource dataSource() {       BasicDataSource dataSource = new BasicDataSource();       dataSource.setDriverClassName("com.mysql.jdbc.Driver");       dataSource.setUrl("jdbc:mysql://localhost:3306/dummydb");       dataSource.setUsername("dummy_user");       dataSource.setPassword("dummy_password");       return dataSource;   }   @Bean   public SqlSessionFactory sqlSessionFactory(){       SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();       sqlSessionFactoryBean.setDataSource(dataSource());       try {           return sqlSessionFactoryBean.getObject();       } catch (Exception e) {           throw new RuntimeException(e);       }   }   @Bean   public MapperScannerConfigurer mapperScanner(){       MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();       mapperScannerConfigurer.setBasePackage("com.haier.demo.dao");       return mapperScannerConfigurer;   }}

该文件用以代替spring-web-config.xml

 

DummyController.java

package com.haier.demo.controller;import com.haier.demo.model.DummyModel;import com.haier.demo.service.IDummyService;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.web.bind.annotation.*;@RestController@Configuration@ComponentScan("com.haier.demo.service")public class DummyController {   private final Logger logger = LoggerFactory.getLogger(DummyController.class);   @Autowired   private IDummyService dummyService;   /**    * @author: yunpeng.liu    * @date: 11/11/16    * @http_method: GET    * @url: http://localhost:9080/dummy_get?name=li&gender=0    * @param name    * @param gender    * @return    */   @RequestMapping(           value = "/dummy_get",           method = RequestMethod.GET,           produces = "application/json")   public DummyModel get(@RequestParam("name") String name, @RequestParam("gender") int gender) {       logger.debug("DummyController.get()");       return dummyService.findById(1);   }   /**    * @author: yunpeng.liu    * @date: 11/11/16    * @http_method: POST    * @url: http://localhost:9080/dummy_post    * @param model    * @return    */   @RequestMapping(           value = "/dummy_post",           method = RequestMethod.POST,           produces = "application/json")   public DummyModel post(@RequestBody DummyModel model) {       logger.debug("DummyController.post()");       DummyModel response = new DummyModel();       dummyService.insert(model);       return response;   }}

 

DummyDAO.java

package com.haier.demo.dao;import com.haier.demo.model.DummyModel;import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update;import java.util.List;public interface DummyDAO {   @Insert("insert into user (name,gender) values(#{name},#{gender})")   public int insert(DummyModel dummyModel);   @Update("update user set name=#{username},gender=#{gender} where id=#{id}")   public int update(DummyModel dummyModel);   //推荐使用update delete_flag字段进行软删除   @Delete("delete from user where id=#{id}")   public int delete(int id);   @Select("select * from user ")   public List
selectAll(); @Select("select * from user where id=#{id}") public DummyModel findById(int id);}

 

DummyModel.java

package com.haier.demo.model;import com.fasterxml.jackson.annotation.JsonProperty;public class DummyModel {   @JsonProperty("id")   private int id;   @JsonProperty("name")   private String name;   @JsonProperty("gender")   private boolean gender;   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 boolean isGender() {       return gender;   }   public void setGender(boolean gender) {       this.gender = gender;   }}

 

DummyService.java

package com.haier.demo.service;import com.haier.demo.dao.DummyDAO;import com.haier.demo.model.DummyModel;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;@Servicepublic class DummyService implements IDummyService{   private static final Logger logger = LoggerFactory.getLogger(DummyService.class);   @Autowired   private DummyDAO dummyDAO;   public DummyDAO getDummyDAO(){       return dummyDAO;   }   public void setDummyDAO(DummyDAO dummyDAO){       this.dummyDAO = dummyDAO;   }   public int delete(int id) {       return this.dummyDAO.delete(id);   }   public DummyModel findById(int id) {       return this.dummyDAO.findById(id);   }   public int insert(DummyModel dummyModel) {       return this.dummyDAO.insert(dummyModel);   }   public List
selectAll() { return this.dummyDAO.selectAll(); } public int update(DummyModel dummyModel) { return this.dummyDAO.update(dummyModel); }}

 

IDummyService.java

package com.haier.demo.service;import com.haier.demo.model.DummyModel;import java.util.List;public interface IDummyService {   public int insert(DummyModel dummyModel);   public int update(DummyModel dummyModel);   public int delete(int id);   public List
selectAll(); public DummyModel findById(int id);}

 

WebInitializer.java

package com.haier.demo.utils;import com.haier.demo.config.SpringCoreConfig;import com.haier.demo.config.SpringWebConfig;import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{   @Override   protected Class
[] getRootConfigClasses() { return new Class[] { SpringCoreConfig.class }; } @Override protected Class
[] getServletConfigClasses() { return new Class[] { SpringWebConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; }}

该文件用以替代web.xml。

 

五、配置tomcat,运行项目

 

PS. 还有很多地方没有完善,没有 AOP 来控制权限并记录日志,没有反射简化 Service 。呐,回头加。

转载于:https://my.oschina.net/u/1040430/blog/787443

你可能感兴趣的文章
一周小程序学习 第1天
查看>>
小孩的linux
查看>>
SpringMVC、MyBatis声明式事务管理
查看>>
开发者详解:端游及手游服务端的常用架构
查看>>
动态保持视频文件存取容量VC
查看>>
javascript去掉字符串前后空格
查看>>
JavaScript History对象
查看>>
在 Windows 下安装 Oracle 11g XE (Express Edition)
查看>>
ListView优化
查看>>
【原创】 PostgreSQL 实现MySQL 的auto_increment 字段
查看>>
php闭包语法学习
查看>>
在子线程中弹土司的一段代码
查看>>
[Android]关于Root
查看>>
apache下配置php
查看>>
vs2015添加vc助手
查看>>
检测点1.1
查看>>
android--------阿里 AndFix 热修复
查看>>
平面设计现在行业发展如何?
查看>>
如果想做数据标注,你可能会遇到哪些坑?
查看>>
Jenkins+Ant+TestNG+Testlink自动化构建集成
查看>>