【发布时间】:2017-08-22 07:33:13
【问题描述】:
我的应用程序包含以下类:
SpringMainApplication:
@SpringBootApplication
@ComponentScan(basePackages = {"com.foo"})
class com.foo.appl.SpringMainApplication {
... some code...
}
应该用于自动装配字段的接口:
interface com.foo.bar.ClassToAutowire {
}
还有另一个使用该接口作为字段的类:
@Component
class com.foo.appl.pack.ImplementationClass {
@Autowired
ClassToAutowire autoClass;
@Scheduled(fixedRate = 60000)
public void startStuff() {
// do something...
}
}
但该字段不会自动装配:
com.foo.appl.pack.ImplementationClass 中的字段 autoClass 需要一个 找不到类型为“com.foo.bar.ClassToAutowire”的 bean。
行动:
考虑在你的 配置。
我猜 Spring 不喜欢我的包结构?
com.foo.bar.ClassToAutowire
com.foo.appl.SpringMainApplication
com.foo.appl.pack.ImplementationClass
@SpringBootApplication 是否必须在根包中并且所有组件都必须在子包中?如果是这样,我该如何解决我的“问题”,因为 ClassToAutowire 来自导入的 JAR。
将basePackge 更改为com.foo.bar 时,应用程序启动,但计划的方法不会运行。
谢谢
【问题讨论】:
-
将您的
SpringMainApplication放入com.foo或将@ComponentScan("com.foo")添加到您的SpringMainApplication。 -
虽然将
SpringMainApplication放入com.foo可以解决我的问题,但我想保持我的包结构不变...@ComponentScan("com.foo")已添加到 SpringMainApplication。 -
这是您在顶级包中的起点的最佳实践。如我的评论中所述,如果您真的不希望这样做(这有几个缺点,尤其是在开始使用更多框架时)添加
@ComponentScan("com.foo"),但例如这不会自动检测 Spring Data 存储库、JPA 实体等。您将需要一个很多额外的配置,否则你可以免费获得。
标签: java spring spring-boot component-scan