lcmxiaoya

导航

构建你的spring boot代码

Spring boot不需要任何特定的代码布局来工作。然而,有一些最佳实践可以帮助您。

 

1、避免使用缺省包

当一个类不包含包声明时,它被认为是在“缺省包”中。“默认包”的使用通常是不鼓励的,应该避免。对于使用 @ComponentScan@EntityScan, or @SpringBootApplication注释的Spring boot应用程序来说,它可能会引起特别的问题,因为每个jar中的每个类都被读取。

 

我们建议您遵循Java的推荐包命名约定,并使用反向的域名(例如,com.example.project)。

 

2、定位主应用程序类

我们通常建议您将主应用程序类放在根包中,放在其他类之上。@EnableAutoConfiguration 注释通常放置在您的主类上,它隐式地为某些项目定义了一个基本的“搜索包”。例如,如果您正在编写一个JPA应用程序,则使用@EnableAutoConfiguration 注释类的包来搜索@entity项。

 

在不需要指定basePackage属性的情况下,使用根包也可以使用@ComponentScan 注释。如果您的主类位于根包中,您也可以使用@SpringBootApplication 注释。

 

下面的清单显示了一个典型的布局:

com
 +- example
     +- myapplication
         +- Application.java
         |
         +- customer
         |   +- Customer.java
         |   +- CustomerController.java
         |   +- CustomerService.java
         |   +- CustomerRepository.java
         |
         +- order
             +- Order.java
             +- OrderController.java
             +- OrderService.java
             +- OrderRepository.java


Application.java入口程序的代码如下所示:
package com.example.myapplication;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {

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

}

posted on 2018-04-01 11:59  lcmxiaoya  阅读(169)  评论(0编辑  收藏  举报