一、创建项目
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 ListselectAll(); @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 ListselectAll() { 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 ListselectAll(); 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 。呐,回头加。