第一章 spring boot实例项目快速搭建

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第一章 spring boot实例项目快速搭建相关的知识,希望对你有一定的参考价值。

环境说明:由于此次主要是学习spring cloud,故例子程序都进行简化,没有service层。数据库持久层使用JPA,数据库使用内嵌的H2。web使用spring mvc,项目构建使用maven,IDE使用myeclipse,jdk 1.8,spring boot使用。

(1)服务提供者项目搭建过程:

      pom.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.antsoldier</groupId>
    <artifactId>provider</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>provider</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
    
        <!-- 此处说明数据库持久层使用JPA -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        
        <!-- 此处说明web层使用spring mvc -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


        <!-- 此处说明使用内嵌数据库 H2 -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        
        <!-- 使用spring boot框架 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

在classpath下添加启动配置文件:

application.yml

server:
  port: 8083
spring:
  jpa:
    generate-ddl: false
    show-sql: true
    hibernate:
      ddl-auto: none
  datasource:
    platform: h2
    schema: classpath:database.sql
    data: classpath:data.sql
logging:
  level:
    root: INFO
    org.hibernate: INFO
    org.hibernate.type.decriptor.sql.BasicBinder: TRACE
    org.hibernate.type.decriptor.sql.BasicExtractor: TRACE
    com.itmuch: DEBUG

注意:

server:
  port: 8083  代表tomcat启动端口
schema: classpath:database.sql   代表开始执行的建表语句
data: classpath:data.sql         代表初始化插入数据

在classpath下建立
database.sql文档,用来初始化数据库表。
drop table user if exists;
create table user(id bigint,
username varchar(20),
name varchar(20),
age int);
在classpath下建立data.sql文档,用来为表添加数据。
insert into user(id,username,name,age) values(1,user1,name1,20);
insert into user(id,username,name,age) values(2,user2,name2,21);
insert into user(id,username,name,age) values(3,user3,name3,23);
insert into user(id,username,name,age) values(4,user4,name4,24);

 

在com.antsoldier.model包下创建User类

package com.antsoldier.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User implements Serializable{
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    
    @Column
    private String username;
    
    @Column
    private String name;
    
    @Column
    private int age;
    
    
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    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;
    }
    
}

 

在com.antsoldier.dao包下创建UserDao类,作为dao层

package com.antsoldier.dao;

import com.antsoldier.model.User;
import org.springframework.data.jpa.repository.JpaRepository;


public interface UserDao extends JpaRepository<User,Long>{

}

 

在com.antsoldier.controller下创建UserController类,作为controller层

package com.antsoldier.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.antsoldier.dao.UserDao;
import com.antsoldier.model.User;


@RestController
public class UserController {
    
    @Autowired
    private UserDao userDao;
    
    
    @GetMapping("/user/findById/{id}")
    public User findById(@PathVariable Long id){
        return userDao.findOne(id);
    }

}

 

主启动程序:

package com.antsoldier;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(ProviderApplication.class, args);
    }
}

 

运行主启动程序:输入网址:http://localhost:8083/user/findById/1

                       测试服务提供方成功如下:

技术分享

 

 

(2)服务消费方项目搭建如下:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.antsoldier</groupId>
    <artifactId>consumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>consumer</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

 

在classpath下添加启动配置文件:

application.yml

server:
  port: 8073
userServicePath: http://localhost:8083
注意:userServicePath是服务提供方地址

在com.antsoldier.model包下创建User类
package com.antsoldier.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User implements Serializable{
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    
    @Column
    private String username;
    
    @Column
    private String name;
    
    @Column
    private int age;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    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;
    }
    
}

 

在com.antsoldier.controller下创建UserConsumerController类,用来调用远程服务:

package com.antsoldier.controller;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.antsoldier.model.User;


@RestController
public class UserConsumerController {
    
    @Resource
    private RestTemplate restTemplate;  //需要在主程序中配置此对象
    
    @Value("${userServicePath}")
    private String userServicePath;
    
    @GetMapping(value="/userConsumer/{id}")
    public User findById(@PathVariable Long id){
        return restTemplate.getForObject(userServicePath + "/user/findById/"+id, User.class);
    }
}

注意  @Value就是用来加载application.yml文件中的userServicePath值。

 restTemplate对象,需要自己生成,此处为了简单直接在,主程序中生成对象

 

 

主启动程序:

package com.antsoldier;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class ConsumerApplication {
    
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }
}

 

运行主启动程序:输入网址:http://localhost:8073/userConsumer/1

                       测试消费方成功如下:

技术分享

 

 

注意事项:本人在myeclipse中运行项目时,发现配置文件不起作用经过排查才发现由于项目导入myeclipse时,myeclipse没有识别项目为maven项目,一定要确保项目左上角有M标识:

技术分享

 

 项目下载地址:

链接:http://pan.baidu.com/s/1c12YM1i 密码:nw33

 

 

 

 

 

 

  






以上是关于第一章 spring boot实例项目快速搭建的主要内容,如果未能解决你的问题,请参考以下文章

spring-boot第一章:快速开始

Spring Boot 1-项目快速搭建

第一章 第一个spring boot程序

Spring-Boot快速搭建web项目详细总结

Spring Boot企业微信点餐系统-第一章-课程介绍

Spring Boot入门-快速搭建web项目