项目地址:https://github.com/snjl/springboot.myproject.git
Spring Boot框架本身并没有对工程结构有特别的要求,但是按照最佳实践的工程结构可以帮助我们减少可能会遇见的坑,尤其是Spring包扫描机制的存在,如果您使用最佳实践的工程结构,可以免去不少特殊的配置工作。
典型示例
- root package结构:com.example.myproject
- 应用主类Application.java置于root package下,通常我们会在应用主类中做一些框架配置扫描等配置,我们放在root package下可以帮助程序减少手工配置来加载到我们希望被Spring加载的内容
- 实体(Entity)与数据访问层(Repository)置于com.example.myproject.domain包下
- 逻辑层(Service)置于com.example.myproject.service包下
- Web层(web)置于com.example.myproject.web包下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15com
+- example
+- myproject
+- Application.java
|
+- domain
| +- Customer.java
| +- CustomerRepository.java
|
+- service
| +- CustomerService.java
|
+- web
| +- CustomerController.java
|
创建:
项目结构:
工程构建
在上述基础,构建项目:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29Customer.java
package com.example.myproject.domain;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
public class Customer {
"${com.example.myproject.customer.id}") (
private String id;
"${com.example.myproject.customer.name}") (
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
1 | CustomerService.java |
1 | CustomerController.java |
1 | index.html |
1 | application.properties |
运行项目,访问localhost:8080/customer
也可以test:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29MyprojectApplicationTests.java
package com.example.myproject;
import com.example.myproject.service.CustomerService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
(SpringRunner.class)
public class MyprojectApplicationTests {
private CustomerService customerService;
public void contextLoads() {
}
public void testCustomer() {
customerService.printCustomer();
System.out.println(customerService.getCustomer());
}
}
输出:1
2jl
Customer{id='001', name='jl'}