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

環境說明:因爲這次主要是學習spring cloud,故例子程序都進行簡化,沒有service層。數據庫持久層使用JPA,數據庫使用內嵌的H2。web使用spring mvc,項目構建使用maven,IDE使用myeclipse,jdk 1.8,spring boot使用。java

(1)服務提供者項目搭建過程:web

      pom.xml以下:spring

<?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下添加啓動配置文件:sql

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

注意:apache

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類tomcat

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層mvc

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層app

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

相關文章
相關標籤/搜索