springboot专题学习之hello world

spring boot使用自动化配置的方式,使得可以很方便、快捷得构建一个spring web应用。作为学习spring boot 的第一课,还是先基于spring boot构建一个简单的包含控制层、服务层以及数据层的hello world应用。
首先确保本机上安装了mysql,本应用会直接访问mysql自带的数据库world。
mysql下载地址:www.mysql.com/downloads/
world数据库:

springboot专题学习之hello world_第1张图片

city表结构:
springboot专题学习之hello world_第2张图片

系统要求:

(1)Intellij Idea 2016.03
注册码传送门:idea.lanyus.com/
(2)Mysql 5.7
(3)Java 1.7以上

构建指南:

(1)在Intellij Idea里面新建HelloWorld project,并在pom.xml文件中添加mysql-connector以及mybatis依赖。


    mysql
    mysql-connector-java
    6.0.6


    org.mybatis.spring.boot
    mybatis-spring-boot-starter
    1.3.0


    org.springframework.boot
    spring-boot-starter-web

(2)配置/resources/application.properties数据库参数

spring.datasource.url = jdbc:mysql://localhost:3306/world?useUnicode=true&characterEncoding=UTF-8&autocommit=false&autoReconnect=true&useSSL=false&serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver

(3)根据表city的结构创建city对象

public class City {
    private int id;
    private String name;
    private String countryCode;
    private String district;
    private int population;

    public City(int id ,String name, String countryCode,String district,int population) {
        this.id = id;
        this.name = name;
        this.countryCode=countryCode;
        this.district = district;
        this.population = population;
    }
    
    //setter & getter
}

(4)创建控制层CityController

@RestController
public class CityController {
    @Autowired
    private CityService cityService;

    @RequestMapping(value="/city/{cityName}",method= RequestMethod.GET)
    public City gitCity(@PathVariable("cityName") String cityName) {
        return cityService.getCityByCityName(cityName);
    }
}

(5)创建服务层接口CityService 以及实现类CityServiceImpl
CityService:

public interface CityService {
    /**
     * get City by its name
     * @param cityName
     * @return
     */
    City getCityByCityName(String cityName);
}

CityServiceImpl:

@Service
public class CityServiceImpl implements CityService{

    @Autowired
    private CityMapper cityMapper;

    @Override
    public City getCityByCityName(String cityName) {
        return cityMapper.findCityByCityName(cityName);
    }
}

(6)创建CityMapper,用于读写数据库表City

@Mapper
public interface CityMapper {
    @Select("Select * from city where name=#{cityName}")
    City findCityByCityName(String cityName);
}

运行结果

运行主application,在浏览器里面输入http://localhost:8080/city/shanghai,
结果显示如下:

springboot专题学习之hello world_第3张图片
结果显示.png

代码地址:https://github.com/yhguodu/helloworld

你可能感兴趣的:(springboot专题学习之hello world)