1. 程式人生 > >SpringBoot--多模組開發

SpringBoot--多模組開發

目錄結構:


實現步驟:

1.建立springboot專案--spring-boot-demo。

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.cxb</groupId> <artifactId>spring-boot-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <modules> <module>web</module> <module>persistence</module> <module>model</module>
</modules> <!--修改成 pom --> <!-- 模型層:model 持久層:persistence 表示層:web web依賴persistence, persistence依賴於model --> <packaging>pom</packaging> <name>spring-boot-demo</name> <description>Demo project for Spring Boot</description>
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.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-webflux</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.projectreactor</groupId> <artifactId>reactor-test</artifactId> <scope>test</scope> </dependency> </dependencies> </project>

建立模組web:



一直next,填好模組名稱即可。

web模組的目錄結構:


這裡的web.xml檔案是為了打成war時候新增的。

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">
    <parent>
        <artifactId>spring-boot-demo</artifactId>
        <groupId>com.cxb</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>web</artifactId>
<!--將package值(預設jar)調整成war,這裡就必須新增一個web.xml檔案了 -->
<packaging>war</packaging>
<!--web依賴於persistence-->
    <!--web依賴於model-->
    <!--實現了間接依賴-->
<dependencies>
<!--新增persistence依賴-->
<dependency>
            <groupId>com.cxb</groupId>
            <version>0.0.1-SNAPSHOT</version>
            <artifactId>persistence</artifactId>
        </dependency>
    </dependencies>
<!--這裡需要指明工程啟動的主類,父工程裡邊不需要build這一塊了-->
<build>
<!--加上這個是因為打成war時,編譯出錯了-->
<defaultGoal>compile</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
<!--指定mainClass-->
<configuration>
                    <mainClass>springbootdemo.SpringBootDemoApplication</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
package springbootdemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import springbootdemo.model.User;
import springbootdemo.repository.UserRepository;
import java.util.Collection;
/**
 *  路由器函式配置
 * Created by 81046 on 2018-06-16
 */
@Configuration
public class RouterFunctionConfiguration {

    /**
     * Servlet
     *      請求介面:ServletRequest或者HttpServletRequest
     *      響應介面:ServletResponse或者HttpServletResponse
     *  Spring 5.0 重新定義了服務請求和響應介面
     *      請求介面:ServletRequest
     *      響應介面:ServletResponse
     *  即可支援Servlet 規範,也可以支援自定義,比如 Netty (Web Server)
     *
     *  以本例:
     *      定義GET請求,並且返回所有的使用者物件 URI:/user/findAll
     *      Flux 是0-N個物件集合
     *      Mono 是0-1個物件集合
     *      Reactive 中的Flux 或者 Mono 它是非同步處理 (非阻塞)
     *      集合物件基本上是同步處理 (阻塞)
     *      Flux 或者 Mono 都是 Publisher
     */
@Bean
public RouterFunction<ServerResponse> userFindAll(UserRepository userRepository){
        return RouterFunctions.route(RequestPredicates.GET("/user/list"),
request -> {
                    //返回所有的使用者
Collection<User> users = userRepository.findAll();
Flux<User> userFlux = Flux.fromIterable(users);
                    return ServerResponse.ok().body(userFlux,User.class);
});
}
}
package springbootdemo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springbootdemo.model.User;
import springbootdemo.repository.UserRepository;
import java.util.Collection;
/**
 * Created by 81046 on 2018-06-16
 */
@RestController
@RequestMapping("/user")
//RestController 等價於controller和responseBody
public class UserController {

    private final UserRepository userRepository;
/**
     *  這裡是採用構造器的注入方式注入userRepository
     *  好處是提前初始化,不能修改
     *  @Autowired 可寫可不寫
     */
@Autowired
public UserController(UserRepository userRepository){
        this.userRepository=userRepository;
}

    /**
     *  http://localhost:8080/user/save?name=小石潭記
     * @param name
* @return
*/
@PostMapping("/save")
    public User save(@RequestParam String name){
        User user = new User();
user.setName(name);
        if (userRepository.save(user)){
            System.out.println("儲存物件成功:" + user);
}
        return user;
}

    @GetMapping("/list")
    public Collection<User> list(){
        return userRepository.findAll();
}

}
package springbootdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootDemoApplication {

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

這裡web模組就完成了,注意該模組需要依賴其他模組的檔案,依賴在該模組pom.xml檔案中。

多模組就是為了職責分明,web模組只做web端的訪問,model模組就是用來管理實體類的,persistence模組就是管理資料庫打交道的。

接下來介紹model模組和persistence模組。

建立模板的方式和前面的web模組一樣。

model模組目錄結構:


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">
    <parent>
        <artifactId>spring-boot-demo</artifactId>
        <groupId>com.cxb</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>model</artifactId>
</project>
package springbootdemo.model;
/**
 * Created by 81046 on 2018-06-16
 */
public class User {
    private int id;
    private String name;
    public int getId() {
        return id;
}

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

    public String getName() {
        return name;
}

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

    public User() {
    }

    @Override
public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
}
}

persistence模組目錄結構:


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">
    <parent>
        <artifactId>spring-boot-demo</artifactId>
        <groupId>com.cxb</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>persistence</artifactId>
    <dependencies>
<!--新增模型依賴-->
<dependency>
            <groupId>com.cxb</groupId>
            <version>0.0.1-SNAPSHOT</version>
            <artifactId>model</artifactId>
        </dependency>
    </dependencies>
</project>

package springbootdemo.repository;
import org.springframework.stereotype.Repository;
import springbootdemo.model.User;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
 * Created by 81046 on 2018-06-16
 */
@Repository
public class UserRepository {

    /**
     * 採用記憶體型的儲存方式-->Map
     */
private final ConcurrentMap<Integer,User> repository = new ConcurrentHashMap<>();
/**
     * id生成器
     */
private final static AtomicInteger idGennerator = new AtomicInteger();
/**
     * 儲存使用者物件
     */
public boolean save(User user){
        int id = idGennerator.incrementAndGet();
user.setId(id);
        return repository.put(id,user) == null ;
}

    /**
     * 查詢所有的使用者
     * @return
*/
public Collection<User> findAll(){
        return repository.values();
}
}

這裡就完成了三個模組的實現,注意每個模組的包名保持一致,這裡包名全是springbootdemo,然後在下面建立具體的包即可。

再介紹一下打包的方式:

1.jar     在該檔案的位置執行cmd     執行mvn -Dmaven.test.skip -U clean package




這裡jar的方式介紹完了,war只是將pom檔案中的jar改成war