SpringBoot 官方推荐我们这样放置 Application 启动类

Springboot 的官方建议

Springboot 官方在创建 Springboot 项目时给出了如下两点建议:

  1. 项目中的类需要放在包下面, 不要直接把类直接放在 src/main/java/ 目录下.
  2. 推荐把启动类放在其他类所在包的最外层.

官方推荐的项目目录如下所示:

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 官方文档中还提到, 可以用 @EnableAutoConfigurationand @ComponentScan组合注解用来替代 @SpringBootApplication注解, 如下所示:

@EnableAutoConfiguration
@ComponentScan(basePackages = {"com.example.demo"})
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值