使用注释@SpringBootApplication进行配置

我有Spring Boot配置的问题。

我使用https://start.spring.io/创建了基本的Spring Boot项目

我有一个问题,配置仅适用于子目录中的类:

在此处输入图像描述

我试过注释@ComponentScan但它没有帮助。

你知道我能用这个做什么吗?

@SpringBootApplication的Spring Boot文档说明

许多Spring Boot开发人员总是使用@Configuration @EnableAutoConfiguration@ComponentScan @EnableAutoConfiguration@ComponentScan注释其主类。 由于这些注释经常一起使用(特别是如果您遵循上面的最佳实践),Spring Boot提供了一个方便的@SpringBootApplication替代方案。

@SpringBootApplication注释等同于使用@Configuration @EnableAutoConfiguration@ComponentScan @EnableAutoConfiguration@ComponentScan及其默认属性 :[…]

@ComponentScan javadoc所在的位置

如果未定义特定包,则将从声明此批注的类的包进行扫描。

也就是说,只扫描与ReadingListApplication在同一个包中的类型。

如果需要自定义配置,请根据需要提供自己的@Configuration @EnableAutoConfiguration@ComponentScan @EnableAutoConfiguration@ComponentScan

在设置Spring boot项目时,请使用Application类(在基础包中包含@SpringBootApplication注释的类)。

@SpringBootApplication所做的一件事是组件扫描。 但是,它只扫描子包 。 即如果你将该类放在com.mypackage中 ,那么它将扫描子包中的所有类,即com.mypackage。*。

如果您不想这样做,您还可以将@ComponentScan添加到指定根包的类,即@ComponentScan("com.mypackage")

我建议你有一个基本包,即com.mypackage 。 在这些包中,有你的子包。 您是否在该基础包中包含@SpringBootApplication

检查Spring文档:

http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/SpringBootApplication.html

您可以使用@SpringBootApplication覆盖组件扫描的默认值。 您只需将其作为参数包含在内:

@SpringBootApplication(scanBasePackages = "entertainment")

或字符串数​​组:

@SpringBootApplication(scanBasePackages = {"entertainment", "readinglist"})

我遇到了同样的问题,为了解决这个问题,我重命名了这样的软件包。

“com.project”

在那里你可以放置你的SpringBootAplication主类,然后只需创建以“com.project”开头的其他包

“com.project.dao”

“com.project.controller”

创建这个子项目结构时,您无需在@SpringBootApplication注释中使用scanBasePackages,这样您的主类就能够找到项目中的每个组件。

如果您选择使用scanBasePackages,请记住您需要像这样设置所有组件包

@SpringBootApplication(scanBasePackages = {“com.project.dao”,“com.project.controller”})