java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Springboot分模块搭建

Springboot分模块项目搭建的实现

作者:GreaterBuilder

在软件开发中,利用Spring Boot进行分模块项目搭建能够提高代码的模块化和复用性,本文主要介绍了Springboot分模块项目搭建的实现,感兴趣的可以了解一下

一、创建聚合父工程

(1) eclipse -> File -> new -> Other… -> Maven -> Maven Project

在这里插入图片描述

(2) configure project

在这里插入图片描述

(3) pom.xml配置

<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">
	<description>SpringBoot分模块</description>
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.button</groupId>
	<artifactId>springboot-parent</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>pom</packaging>
	
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
		<springboot-web.version>0.0.1-SNAPSHOT</springboot-web.version>
		<springboot-service.version>0.0.1-SNAPSHOT</springboot-service.version>
		<springboot-dao.version>0.0.1-SNAPSHOT</springboot-dao.version>
		<springboot-entity.version>0.0.1-SNAPSHOT</springboot-entity.version>
		<mybatis-spring-boot-starter.version>1.1.1</mybatis-spring-boot-starter.version>
		<HikariCP.version>2.4.13</HikariCP.version>
		<pagehelper.version>5.0.0</pagehelper.version>
		<pagehelper-spring-boot-autoconfigure.version>1.2.3</pagehelper-spring-boot-autoconfigure.version>
		<pagehelper-spring-boot-starter.version>1.2.3</pagehelper-spring-boot-starter.version>
		<json-lib.version>2.2.2</json-lib.version>
	</properties>

	<!-- 这里继承SpringBoot提供的父工程 -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.1.RELEASE</version>
		<relativePath />
	</parent>
	<!-- 这里声明多个子模块 -->
	<modules>
		<module>springboot-web</module>
		<module>springboot-service</module>
		<module>springboot-dao</module>
		<module>springboot-entity</module>
	</modules>
	
	<!-- 这里统一管理依赖的版本号 -->
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>com.button</groupId>
				<artifactId>springboot-web</artifactId>
				<version>${springboot-web.version}</version>
			</dependency>
			<dependency>
				<groupId>com.button</groupId>
				<artifactId>springboot-service</artifactId>
				<version>${springboot-service.version}</version>
			</dependency>
			<dependency>
				<groupId>com.button</groupId>
				<artifactId>springboot-dao</artifactId>
				<version>${springboot-dao.version}</version>
			</dependency>
			<dependency>
				<groupId>com.button</groupId>
				<artifactId>springboot-entity</artifactId>
				<version>${springboot-entity.version}</version>
			</dependency>
			<dependency>
				<groupId>org.mybatis.spring.boot</groupId>
				<artifactId>mybatis-spring-boot-starter</artifactId>
				<version>${mybatis-spring-boot-starter.version}</version>
			</dependency>
			<!--mysql链接依赖 -->
			<dependency>
				<groupId>com.zaxxer</groupId>
				<artifactId>HikariCP-java7</artifactId>
				<version>${HikariCP.version}</version>
			</dependency>
			<!-- 分页插件pagehelper -->
			<dependency>
				<groupId>com.github.pagehelper</groupId>
				<artifactId>pagehelper</artifactId>
				<version>${pagehelper.version}</version>
			</dependency>
			<dependency>
				<groupId>com.github.pagehelper</groupId>
				<artifactId>pagehelper-spring-boot-autoconfigure</artifactId>
				<version>${pagehelper-spring-boot-autoconfigure.version}</version>
			</dependency>
			<dependency>
				<groupId>com.github.pagehelper</groupId>
				<artifactId>pagehelper-spring-boot-starter</artifactId>
				<version>${pagehelper-spring-boot-starter.version}</version>
			</dependency>
			<!-- json -->
			<dependency>
				<groupId>net.sf.json-lib</groupId>
				<artifactId>json-lib</artifactId>
				<version>${json-lib.version}</version>
				<classifier>jdk15</classifier>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<!-- java编译插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

二、创建springboot-web

(1) 右键点击父工程 -> new -> Other… -> Maven -> Maven Module

在这里插入图片描述

(2) pom.xml

<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>
	<artifactId>springboot-web</artifactId>
	<packaging>jar</packaging>
	<name>springboot-web</name>
	<parent>
		<groupId>com.button</groupId>
		<artifactId>springboot-parent</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<!-- Web模块相关依赖 -->
	<dependencies>
		<dependency>
			<groupId>com.button</groupId>
			<artifactId>springboot-service</artifactId>
		</dependency>
		<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>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
			<scope>true</scope>
		</dependency>
	</dependencies>
	<!--只需在启动类所在模块的POM文件:指定打包插件 -->
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
					<fork>true</fork><!-- 没有该配置,devtools 不生效 -->
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

解释:
pom文件中的如下配置:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-devtools</artifactId>
	<optional>true</optional>
	<scope>true</scope>
</dependency>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <!-- 没有该配置,devtools 不生效 -->
                <fork>true</fork>
            </configuration>
        </plugin>
    </plugins>
</build>

如上的两项配置,添加之后会打开springboot的热部署,这样每次修改文件之后,不用手动重新启动项目。配置热部署可以让项目自动加载变化的文件,省去的手动操作。(项目搭建好之后,启动项目,随便创建/修改一个文件并保存,会发现控制台打印 springboot 重新加载文件的log。)

三、创建springboot-service

参照如上创建方式

pom.xml

<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>
	<artifactId>springboot-service</artifactId>
	<packaging>jar</packaging>
	<name>springboot-service</name>
	<parent>
		<groupId>com.button</groupId>
		<artifactId>springboot-parent</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>com.button</groupId>
			<artifactId>springboot-dao</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
		</dependency>
	</dependencies>
</project>

四、创建springboot-dao

参照如上创建方式

pom.xml

<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>
	<artifactId>springboot-dao</artifactId>
	<packaging>jar</packaging>
	<name>springboot-dao</name>
	<parent>
		<groupId>com.button</groupId>
		<artifactId>springboot-parent</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>com.button</groupId>
			<artifactId>springboot-entity</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-aop</artifactId>
		</dependency>
		<!--数据库连接jdbc依赖 -->
		<!-- JDBC连接数据库,因为要用HikariCP,所以需要将SpringBoot中的tomcat-jdbc排除 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
			<exclusions>
				<exclusion>
					<groupId>org.apache.tomcat</groupId>
					<artifactId>tomcat-jdbc</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<!-- mybatis -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
		</dependency>
		<!--mysql链接依赖 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<dependency>
			<groupId>com.zaxxer</groupId>
			<artifactId>HikariCP-java7</artifactId>
		</dependency>

		<!-- 分页插件pagehelper -->
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
		</dependency>
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper-spring-boot-autoconfigure</artifactId>
		</dependency>
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper-spring-boot-starter</artifactId>
		</dependency>
	</dependencies>
	<build>
		<!-- 一定要声明如下配置 -->
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*.xml</include>
				</includes>
			</resource>
		</resources>
	</build>
</project>

五、创建springboot-entity

参照如上创建方式

pom.xml

<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>
	<artifactId>springboot-entity</artifactId>
	<packaging>jar</packaging>
	<name>springboot-entity</name>

	<parent>
		<groupId>com.button</groupId>
		<artifactId>springboot-parent</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
</project>

六、项目代码

1、springboot-dao

①UserMapper.java

package com.button.project.dao;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import com.button.project.pojo.UserModel;

@Mapper
public interface UserMapper {
	List<UserModel> getUser();
}

②mapper/UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.button.project.dao.UserMapper">

    <resultMap id="user" type="map">  
        <result column="id" property="id" javaType="integer"/>  
        <result column="name" property="name" javaType="String"/>  
        <result column="age" property="age" javaType="integer"/>  
    </resultMap> 
	
	<select id="getUser" resultType="com.button.project.pojo.UserModel">
	   SELECT 
	       *
	   FROM
	       tb_user
	</select>
</mapper>

③config/application-mybatis.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd ">
	<bean id="txManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<tx:annotation-driven transaction-manager="transactionManager" />
</beans>

2、springboot-entity

UserModel.java

package com.button.project.pojo;

import java.io.Serializable;

public class UserModel implements Serializable{
	private static final long serialVersionUID = 1L;
	private Integer id;
	private String name;
	private Integer age;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "UserModel [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
}

3、springboot-service

①UserService.java

package com.button.project.service;

import java.util.List;

import com.button.project.pojo.UserModel;

public interface UserService {
	List<UserModel> getUser();
}

②UserServiceImpl.java

package com.button.project.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.button.project.dao.UserMapper;
import com.button.project.pojo.UserModel;
import com.button.project.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserMapper userMapper;
	
	@Override
	public List<UserModel> getUser() {
		return userMapper.getUser();
	}

}

4、springboot-web

①UserController.java

package com.button.project.controller;

import java.util.List;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.button.project.pojo.UserModel;

@RequestMapping(value = "/user", produces = "application/json;charset=UTF-8")
public interface UserController {
	
	@RequestMapping(value = "/getUser", method={RequestMethod.POST, RequestMethod.GET})
    List<UserModel> getUser();
}

②UserControllerImpl.java

package com.button.project.controller.impl;

import java.util.List;

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

import com.button.project.controller.UserController;
import com.button.project.pojo.UserModel;
import com.button.project.service.UserService;

@RestController
public class UserControllerImpl implements UserController {
	
	@Autowired
	private UserService userService;
	
	@Override
	public List<UserModel> getUser() {
		return userService.getUser();
	}

}

③SpringBootApplicationService

package com.button.project;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ImportResource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@ImportResource("classpath:config/application-mybatis.xml")
@ServletComponentScan
@EnableCaching
@EnableTransactionManagement
@SpringBootApplication
public class SpringBootApplicationService {
	//项目启动入口
	public static void main(String[] args) {
		SpringApplication.run(SpringBootApplicationService.class, args);
	}
}

④InitConstantListener.java

package com.button.project.init;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@WebListener
public class InitConstantListener implements ServletContextListener {
	private static final Logger logger = LoggerFactory.getLogger(InitConstantListener.class);
	
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		logger.info("初始化数据.");
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		logger.info("销毁数据.");
	}
}

⑤application.yml

server:
    servlet:
        context-path: /button
    port: 8080
    uri-encoding: utf-8
    
logging: 
    config: classpath:logback.xml
    
spring: 
    dataSource: 
        url: jdbc:mysql://*********:3306/button-pro?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&allowMultiQueries=true&useSSL=true
        username: *****
        password: ******
        driver-class-name: com.mysql.jdbc.Driver
        type: com.zaxxer.hikari.HikariDataSource
        hikari:
            minimum-idle: 5
            maximum-pool-size: 15
            idle-timeout: 30000
            pool-name: DatebookHikariCP
            max-lifetime: 1800000
            connection-timeout: 30000
            connection-test-query: 'SELECT 1'

mybatis:
    # 加载mapper
    mapper-locations: "classpath:mapper/*.xml"

mapper:
    not-empty: false
    identity: MYSQL
    
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql

⑥logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="30 seconds">
    <property name="LOG_HOME" value="/com/button/" />

	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
		<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} -%msg%n</pattern>
		</encoder>
	</appender>
	<appender name="FILE"
		class="ch.qos.logback.core.rolling.RollingFileAppender">
		<file>${LOG_HOME}/springboot.log</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<FileNamePattern>
				${LOG_HOME}/springboot.log.%d{yyyy-MM-dd}.%i.log
			</FileNamePattern>
			<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>100MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
		</rollingPolicy>
		<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
			<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} -%msg%n</pattern>
		</encoder>
	</appender>

	<root level="DEBUG">
		<appender-ref ref="STDOUT" />
		<appender-ref ref="FILE" />
	</root>
</configuration>

七、完整项目结构如下:

在这里插入图片描述

注:一个项目从开发,测试再到生产,可能会使用到不同的配置信息,每次去修改application.yml文件中的信息就显得特别麻烦,可以使用如下方式解决。
比如项目运行环境开发(dev),测试(test),生产(prod),我们可以在src/main/resources文件夹下创建如下四个文件:
application-dev.yml

server:
    servlet:
        context-path: /button-dev
    port: 8080
    uri-encoding: utf-8

application-test.yml

server:
    servlet:
        context-path: /button-test
    port: 8081
    uri-encoding: utf-8

application-prod.yml

server:
    servlet:
        context-path: /button-prod
    port: 8082
    uri-encoding: utf-8

这三个文件配置好项目不同环境的配置信息
application.yml文件配置如下:

spring:
    profiles:
        active: dev

解释:active后可以配置dev、test、prod,不同的配置会去加载不同的配置信息,这样就不用来回修改配置信息了。

更多springboot内容,请查询官方文档
https://docs.spring.io/spring-boot/docs/1.5.8.RELEASE/reference/html/

源码地址:https://gitee.com/superbutton/SpringBoot-Components/tree/develop/SpringBoot-Moudle

到此这篇关于Springboot分模块项目搭建的实现的文章就介绍到这了,更多相关Springboot分模块搭建内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文