Create a project

Creating a SpringBoot project is so simple that you don’t even need to mention it here. You can create a Spring Boot project by selecting Spring Initlalize when creating a new project with IDEA, or by using the Spring Boot project generation page provided by Spring.

If you already have a Spring Boot project, you can skip this section.

  1. Open start. Spring. IO /

  2. Fill in the group and Artifact information, and select dependencies (I chose Spring Web and Lombok).

  3. Click the Generate button to download the project.

  4. Open the downloaded project and delete the useless.mvn folders, MVNW, mvnw.cmd, and help.md files.

Now that we have an initial Spring Boot project, let’s import it directly into IDEA and take a look at the contents of 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.5. RELEASE</version>
		<relativePath/> <! -- lookup parent from repository -->
	</parent>
	<groupId>com.wdbyte</groupId>
	<artifactId>springboot-module-demo</artifactId>
	<version>0.0.1 - the SNAPSHOT</version>
	<name>springboot-module-demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

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

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>
Copy the code

Adjust the directory structure to the one you want, then add controller and Entity for testing.

ProductController class source code.

@RestController
@RequestMapping("/product")
public class ProductController {

    /** * Get the list of products **@return* /
    @GetMapping("/list")
    public Map list(a) {
        // Simulate query product logic
        Product product = new Product();
        product.setProductName("Millet gruel");
        product.setProductPrice(new BigDecimal(2.0));
        product.setProductStock(100);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code".000);
        resultMap.put("message"."Success");
        resultMap.put("data", Arrays.asList(product));
        returnresultMap; }}Copy the code

Product class source code.

@Data
public class Product {
    /** The name of the commodity
    private String productName;
    /** Commodity price. */
    private BigDecimal productPrice;
    /** Inventory of goods. * /
    private int productStock;
}
Copy the code

modular

With the help of IDEA tool, the project can be quickly transformed into Maven multi-module. Here, we split the demo to be tested into two modules: common and Web. The common module stores entity classes. The Web module holds the Controller layer (although this project is small, it is split for demonstration purposes only). Without further ado, get right to it.

  1. Set the primary POM. XML packaging mode to POM

    <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <! -- Configure the primary POM packaging mode as POM -->
        <packaging>pom</packaging>. .Copy the code
  2. Creating a common module

    Project direct new -> module.

    Select Maven -> Next and fill in the module name.

    Proceed to Next to complete the module creation.

  3. Creating a Web module

    The creation of the Web module is the same as that of the Common module. After the two modules are created, you will find that the Module section is automatically added to your main pom.xml file.

    <modules>
        <module>product-common</module>
    	<module>product-web</module>
    </modules>
    Copy the code
  4. Moves code to the specified module

    Move product. Java to the product-common module, and the rest of the code and resource parts directly to the product-Web module. After you move the code structure, you will look like this.

At this point, the multi-module split is complete, but the red alert in the ProductController code lets you know that things are not over yet.

Dependency management

Dealing with dependencies

You see the red alert in your code, but you immediately realize that because you moved the Product class to the product-common module, there’s no reference here.

Then you look at the contents of the product-common module’s 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>springboot-module-demo</artifactId>
        <groupId>com.wdbyte</groupId>
        <version>0.0.1 - the SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>product-common</artifactId>
</project>
Copy the code

Intelligent in the product-Web module of the POm. XML into the introduction of product-common, hand up and down, easy to fix.

<?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>springboot-module-demo</artifactId>
        <groupId>com.wdbyte</groupId>
        <version>0.0.1 - the SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>product-web</artifactId>
    <dependencies>
        <dependency>
            <groupId>com.wdbyte</groupId>
            <artifactId>product-common</artifactId>
        </dependency>
    </dependencies>
</project>
Copy the code

You quickly click Build-> Build Project and get an Error warning that hurts you with a black eye.

However, you quickly locate the problem. Looking at maven dependencies, you see that there is no version number specified for the product-common dependency.

B: I see. Since we didn’t specify the version number, we’ll just do it. In the outermost primary POM.xml add the

add to specify the dependency and the version number to specify.

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.wdbyte</groupId>
                <artifactId>product-common</artifactId>
                <version>0.0.1 - the SNAPSHOT</version><! -- Maven package default 0.0.1-SNAPSHOT version -->
            </dependency>
        </dependencies>
    </dependencyManagement>
Copy the code

Refresh Maven, find the project has no error, compile successfully, run the launch class, the familiar Spring logo appears.

Optimize the rely on

Yes, the Spring Boot application runs successfully after being converted to multiple modules, but you seem to have found a problem. The common module and the Web module both inherit from the main POM. The main POM has Lombok, Spring Boot Web, and Spring Boot Test dependencies. The common module only uses Lombok, but it inherits the rest of Spring Boot’s dependencies.

  1. Only dependencies used by the common module are moved to the Common module.

    <?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>springboot-module-demo</artifactId>
            <groupId>com.wdbyte</groupId>
            <version>0.0.1 - the SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
        <artifactId>product-common</artifactId>
        <dependencies>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
        </dependencies>
    </project>
    Copy the code
  2. Only the dependencies used by the Web module are moved to the Web module.

    <?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>springboot-module-demo</artifactId>
            <groupId>com.wdbyte</groupId>
            <version>0.0.1 - the SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
        <artifactId>product-web</artifactId>
        
        <dependencies>
            <dependency>
                <groupId>com.wdbyte</groupId>
                <artifactId>product-common</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>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
        </dependencies>
    </project>
    Copy the code
  3. Extract the version number used to , where the dependent version of the common module is extracted.

    The contents of the outermost main POM up here look like this.

    <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <packaging>pom</packaging>
        <modules>
            <module>product-common</module>
            <module>product-web</module>
        </modules>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.5. RELEASE</version>
            <relativePath/> <! -- lookup parent from repository -->
        </parent>
        <groupId>com.wdbyte</groupId>
        <artifactId>springboot-module-demo</artifactId>
        <version>0.0.1 - the SNAPSHOT</version>
        <name>springboot-module-demo</name>
        <description>Demo project for Spring Boot</description>
    
        <properties>
            <java.version>1.8</java.version>
            <product-common.version>0.0.1 - the SNAPSHOT</product-common.version>
        </properties>
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>com.wdbyte</groupId>
                    <artifactId>product-common</artifactId>
                    <version>${product-common.version}</version>
                </dependency>
            </dependencies>
        </dependencyManagement>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    </project>
    Copy the code

Look perfect, re-build -> Build Project, find everything is ok, run find everything is ok, access is ok.

Package compiled

Well, it’s the last step, and you feel the dawn of victory shining on your head. Next comes MVN Package.

[INFO] springboot-module-demo ............................. SUCCESS [s] 2.653 [INFO] product - common... Product FAILURE [s] 2.718 [INFO] - web... SKIPPED [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [INFO] Total time: 6.084 s [INFO] Finished at: 2020-03-19T08:15:52+08:00 [INFO] Final Memory: 22M/87M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal Org. Springframework. The boot: spring - the boot - maven - plugin: 2.2.5. RELEASE: repackage (repackage) on project product - common: Execution repackage of goal org. Springframework. The boot: spring - the boot - m the aven - plugin: 2.2.5. RELEASE: repackage failed: Unable to find main class -> [Help 1] [ERROR]Copy the code

The ERROR is upsetting you, but you can see that the spring-boot-maven-plugin is making an ERROR. A second look at your main POM shows that the

compilation plugin uses the spring-boot-maven-plugin.

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

After some thought, move this to the WEB module’S POM, because this is the way Spring Boot is packaged, and all modules now in the main POM will inherit it, so it is definitely not needed for the common module.

Move and repackage. Whether you run the MVN package command or double-click the package in Maven management in IDEA, you will have already repackaged

You can also see the packaged JAR file product-web-0.0.1-snapshot.jar in the target directory under the Web module. You can run it directly using Java commands.

$\ springboot - module - demo \ product - web \ target > Java jar product - web - 0.0.1 - the SNAPSHOT. The jar. ____ _ __ _ _ / \ \ / ___ '_ __ _ _) (_ _ __ __ _ \ \ \ \ (\ ___ () |' _ | '_ | |' _ \ / _ ` | \ \ \ \ \ \ / ___) | | _) | | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.2.5.RELEASE) 2020-03-19 08:33:03.337 INFO 15324 -- [main] com.wdbyte.application: Starting Application v0.0.1-snapshot on DESKTOP -8scfv4m with PID 15324 (C:\Users\83981\ DESKTOP \springboot-mod Ule -demo\product-web\target\ product-web-0.0.1-snapshot. jar started by 83981 in C:\Users\83981\Desktop\ springboot-modole-demo \product-web\target) 2020-03-19 08:33:03.340 INFO 15324 -- [main] com.wdbyte.Application : No active profile set, falling back to default profiles: The default 08:33:04 2020-03-19. 15324-410 the INFO [main] O.S.B.W.E mbedded. Tomcat. TomcatWebServer: Tomcat initialized with port(s): 8080 (HTTP) 08:33:04 2020-03-19. 15324-432 the INFO [main] o.a pache, catalina. Core. StandardService: Starting the service [Tomcat] 2020-03-19 08:33:04. 432 INFO 15324 - [the main] org. Apache. Catalina. Core. StandardEngine: Starting Servlet engine: [Apache Tomcat/9.0.31] 2020-03-19 08:33:04.493 INFO 15324 -- [main] O.A.C.C.C. [Tomcat].[/] : Initializing Spring Embedded WebApplicationContext 2020-03-19 08:33:04.493 INFO 15324 -- [main] o.s.web.context.ContextLoader : Root WebApplicationContext: Initialization completed in 1107 ms 2020-03-19 08:33:04.636 INFO 15324 -- [main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 2020-03-19 08:33:04.769 INFO 15324 -- [main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (HTTP) with context path "2020-03-19 08:33:04.772 INFO 15324 -- [main] com.wdbyte.application: Started Application in 1.924 seconds (JVM running for 2.649) 2020-03-19 08:33:07.087 INFO 15324 -- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'Copy the code

There must be something missing, not only for clarity of structure, but also for the reuse of modules (such as common modules) by other projects. At this point in time, if you have a new project open, relying on common discovery cannot be referenced because you need to install the modules into the local repository. You can click IDEA -> Maven -> install, or use the Maven command.

$\springboot-module-demo> MVN $\springboot-module-demo> MVN -Dmaven.test.skip=true -U clean installCopy the code

Reintroduction found no problem. The code has been uploaded to Github: github.com/niumoo/spri…

Here is the end of this article, if you think good can follow my public number together to communicate. Public account full of dry goods, kid sou no deceit.