SpringBoot Multi-Module 项目分拆为多模块
5个月前 • 276次点击 • 来自 SpringBoot
多模块的好处不言而喻,把大的项目分拆成多个子模块,子模块单独构建,前后端分离,业务较独立的模块重用
参考:
https://spring.io/guides/gs/multi-module/
https://spring.io/guides/gs/accessing-data-jpa/
https://spring.io/guides/gs/rest-service/
分拆
本文构建环境为 STS + SpringBoot2.0.2 + Maven ,将做以下演示:
一个简单CRUD的demo,将数据库操作分拆成demo-db模块用于提供数据库的CRUD,将Restful Api请求分拆为demo-api
- 父工程:demo
- JPA子工程:demo-db
- Restful Api子工程:demp-api
配置完成后demo目录如下:
└── demo-api
└── demo-db
└── mvnw
└── mvnw.cmd
└── pom.xml
同理,分拆其他业务例如demo-web前端,demo-admin后端等等。
demo
使用STS新建父工程demo,删除其他文件,只保留 mvnw / mvnw.cmd / pom.xml
配置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.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<module>demo-db</module>
<module>demo-api</module>
</modules>
</project>
- 此配置标识了demo packaging是pom类型,不是war也不是jar ;
- demo是一个父工程,包含了子工程demo-api和demo-db
demo-db
代码参考以下guide:
https://spring.io/guides/gs/accessing-data-jpa/
使用STS新建demo-db,新建在demo目录下,假设demo的目录是 D:\demo ,那么demo-db新建的目录为 D:\demo\demo-db
demp-api
代码参考以下guide:
https://spring.io/guides/gs/rest-service/
使用STS新建demp-api,新建在demo目录下,假设demo的目录是 D:\demo ,那么demp-api新建的目录为 D:\demo\demp-api
需要注意的一点:demp-api需要调用demo-db提供的Service,在Application中需要配置一下demo-db项目路径**@SpringBootApplication(scanBasePackages = { "com.example.demo.db" })**,如下所示:
@SpringBootApplication(scanBasePackages = { "com.example.demo.db" })
@RestController
public class DemoApiApplication {
private static final Logger log = LoggerFactory.getLogger(DemoApiApplication.class);
@Autowired
CustomerRepository customerRepository;
public static void main(String[] args) {
SpringApplication.run(DemoApiApplication.class, args);
}
@GetMapping("/user/{lastName}")
public List<Customer> home(@PathVariable("lastName") String lastName) {
return customerRepository.findByLastName(lastName);
}
@Bean
public CommandLineRunner demo(CustomerService customerService) {
return (args) -> {
// save a couple of customers
customerService.initCustomers();
};
}
}
Maven打包
进入父工程demo路径下执行:
mvn clean package -Dmaven.test.skip=true