Springboot 的官方建议
Springboot 官方在创建 Springboot 项目时给出了如下两点建议:
- 项目中的类需要放在包下面, 不要直接把类直接放在
src/main/java/
目录下. - 推荐把启动类放在其他类所在包的最外层.
官方推荐的项目目录如下所示:
com
+- example
+- myapplication
+- Application.java
|
+- customer
| +- Customer.java
| +- CustomerController.java
| +- CustomerService.java
| +- CustomerRepository.java
|
+- order
+- Order.java
+- OrderController.java
+- OrderService.java
+- OrderRepository.java
原文链接 请戳这
不走寻常路
如果我们不按常理出牌, 创建出如下的项目结构:
那么就会出现如下错误, 找不到 HelloService 这个 Bean.
Description:
Field helloService in com.example.demo.controller.HelloController required a bean of type 'com.example.demo.service.HelloService' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
为什么报错?
在此之前, 我们先来回顾一下 Spring 是如何通过注解配置 Bean 的.
在 Spring 项目中, 当我们用注解方式配置 Bean 时, 一般都需要在Spring 配置文件中配置包扫描:
<context:component-scan base-package="com.demo.example.controller">
</context:component-scan>
而在 Springboot 中, 却不再需要这一步骤了, 秘密就在于 Springboot 的启动类.
简单来讲, Springboot 启动时, 默认会去 扫描出启动类所在包以及子包 下带 Spring 注解的类. 比如 @Component 、@Service 等.
因此, 在不做相应配置的情况下, 如果你的启动类按照上面那样去 “乱放”, 就会出现上述报错内容, 从而导致项目启动失败.
如何解决
如果我们真有上述那样的必要, 或者我们的 demo 模块需要引用其他模块中的 Bean, 比如(“com.csdn.demo”) 包下面的一些类, 该怎么处理?
答案在启动类上的 @SpringBootApplication
注解中, 该注解提供了一个 scanBasePackages
属性, 通过该属性可以配置要扫描的包, 具体如下所示:
@SpringBootApplication(scanBasePackages = {"com.demo.example", "com.csdn.demo"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
另外, 在 Springboot 官方文档中还提到, 可以用 @EnableAutoConfiguration
and @ComponentScan
组合注解用来替代 @SpringBootApplication
注解, 如下所示:
@EnableAutoConfiguration
@ComponentScan(basePackages = {"com.example.demo"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}