用spring-boot搭建REST服务(maven、mybatis、mysql 、base认证)
用spring-boot搭建REST服务(maven、mybatis、mysql 、base认证)
爱奇途在奇途 发表于2年前
用spring-boot搭建REST服务(maven、mybatis、mysql 、base认证)
  • 发表于 2年前
  • 阅读 176
  • 收藏 2
  • 点赞 0
  • 评论 0

移动开发云端新模式探索实践 >>>   

摘要: 用spring-boot搭建REST服务(maven、mybatis、mysql 、base认证)

运行环境

jdb1.8+   

tomcat8+

IDE:Spring Tool Suite 3.7.1.RELEASE

DB:mysql

持久层框架:mybatis

管本管理:maven

RESTfull测试工具:postman


代码功能

一个Rest查询服务, 查询mysql库中的一张表,返回JSON格式数据

http://localhost:8080/spring-boot-test/test

返回

{
  "code": 0,
  "msg": "hello",
  "result": {
    "id": 1,
    "name": "SAN FRANCISCO",
    "state": "CA",
    "country": "US"
  }
}

其中id、name、state、country是mysql city表的一条记录


主要代码

配置文件
application.properties

#spring.thymeleaf.cache: false
#security.basic.enabled: false


security.user.name=fso
security.user.password=password
#logging.level.org.springframework.security: INFO
#logging.level.org.springframework.boot.actuate.audit.listener.AuditListener: DEBUG


#spring.datasource.schema=import.sql
mybatis.config=classpath:mybatis-config.xml


spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="com.iqitoo.test.model"/>
    </typeAliases>
    <mappers>
        <mapper resource="mapper/CityMapper.xml"/>
    </mappers>
</configuration>


CityMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.iqitoo.test.dao.CityMapper">
    <select id="selectCityById" resultType="City">
        select * from City where id = #{id}
    </select>
</mapper>

数据初始化

CREATE TABLE `city` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `NAME` varchar(45) DEFAULT NULL,
  `STATE` varchar(45) DEFAULT NULL,
  `COUNTRY` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 ;

INSERT INTO CITY (NAME, STATE, COUNTRY) VALUES ('SAN FRANCISCO', 'CA', 'US');


WebXML.java
package com.iqitoo.test;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

public class WebXML extends SpringBootServletInitializer {  
	
    @Override  
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {  
        return application.sources(Application.class);  
    }  
  
}

Application.java
package com.iqitoo.test;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan
@Configuration
@EnableAutoConfiguration
//@SpringBootApplication
public class Application {
	
//	 public static void main(String[] args) {
//	        SpringApplication.run(Application.class, args);
//	}

}

CityService.java
package com.iqitoo.test.service;

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

import com.iqitoo.test.dao.CityMapper;
import com.iqitoo.test.model.City;

@Service
public class CityService{
	
	@Autowired
	private CityMapper mapper;
	
	public City selectCityById(long id){
		
		return mapper.selectCityById(id);
	}
	
}


City.java
package com.iqitoo.test.model;

import java.io.Serializable;

public class City implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Long id;

	private String name;

	private String state;

	private String country;

	public Long getId() {
		return this.id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getState() {
		return this.state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getCountry() {
		return this.country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	@Override
	public String toString() {
		return "City{" +
				"id=" + this.id +
				", name='" + this.name + '\'' +
				", state='" + this.state + '\'' +
				", country='" + this.country + '\'' +
				'}';
	}
}




CityMapper.java
package com.iqitoo.test.dao;

import com.iqitoo.test.model.City;

public interface CityMapper {
	
	public City selectCityById(long id);

}


ResultInfo.java

package com.iqitoo.test.common;

import java.io.Serializable;

public class ResultInfo implements Serializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private int code;
	
	private String msg;
	
	private Object result;

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public Object getResult() {
		return result;
	}

	public void setResult(Object result) {
		this.result = result;
	}
	
	
	

}

TestController.java
package com.iqitoo.test.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.iqitoo.test.common.ResultInfo;
import com.iqitoo.test.model.City;
import com.iqitoo.test.service.CityService;

@RestController
public class TestController {
	
	@Autowired
	private CityService service ;
	
	@RequestMapping("/test")
	public ResultInfo test(
			@RequestParam(value="id", defaultValue="1")
			long id){
		
		ResultInfo info = new ResultInfo();
		
		City city = service.selectCityById(id);
		
		if(city!=null){
			System.out.println(city.getName());
		}
		
		info.setCode(0);
		info.setMsg("hello");
		info.setResult(city);
		
		return info;
		
	}

}


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.iqitoo</groupId>
	<artifactId>spring-boot-test</artifactId>
	<packaging>war</packaging>
	
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-boot-test Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<parent>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-parent</artifactId>  
    <version>1.3.1.RELEASE</version>  
	</parent>  

	<properties>
		<springframe.version>4.1.7.RELEASE</springframe.version>
		
		<logback-ext-spring.version>0.1.1</logback-ext-spring.version>
		<logback.version>1.1.2</logback.version>
	</properties>
	<dependencies>

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>  
            <exclusion>  
                <groupId>org.springframework.boot</groupId>  
                <artifactId>spring-boot-starter-tomcat</artifactId>  
            </exclusion>  
           </exclusions>   
        </dependency>
        <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.0.0</version>
		</dependency>
    	<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
        
        <dependency>  
                <groupId>org.apache.tomcat</groupId>  
                <artifactId>tomcat-servlet-api</artifactId>  
                <version>8.0.30</version>  
                <scope>provided</scope>  
    	</dependency>  
		<dependency>
			<groupId>org.logback-extensions</groupId>
			<artifactId>logback-ext-spring</artifactId>
			<version>${logback-ext-spring.version}</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.2</version>
		</dependency>

	</dependencies>
	<build>
		<finalName>testsecurity</finalName>
		<plugins>
			<!-- <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
           </plugin> -->
            <plugin>  
                <artifactId>maven-compiler-plugin</artifactId>  
                <configuration>  
                	<failOnMissingWebXml>false</failOnMissingWebXml>
                    <source>1.8</source>  
                    <target>1.8</target>  
                </configuration>  
            </plugin>  
           <!--  <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>1.3.1.RELEASE</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin> -->
        </plugins>
	</build>
	
	<pluginRepositories>
    <pluginRepository>
        <id>spring-snapshots</id>
        <url>http://repo.spring.io/snapshot</url>
    </pluginRepository>
    <pluginRepository>
        <id>spring-milestones</id>
        <url>http://repo.spring.io/milestone</url>
    </pluginRepository>
	</pluginRepositories>
</project>


项目目录结构


工程源代码下载    http://pan.baidu.com/s/1eRpIyaQ   

  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 0
博文 1
码字总数 845
×
爱奇途在奇途
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: