1. 程式人生 > >第一章 spring boot實例項目快速搭建

第一章 spring boot實例項目快速搭建

ppi 地址 desc spa .so -m generate ssp get

環境說明:由於此次主要是學習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實例項目快速搭建