Spring boot 在另一个包上找到自动装配 [英] Spring boot find autowired on another package

查看:14
本文介绍了Spring boot 在另一个包上找到自动装配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个使用一些 Spring Data Repository 接口的 Spring Boot 应用程序:

I'm developing a Spring Boot application which uses some Spring Data Repository interfaces:

package test;
@SpringBootApplication
public class Application implements CommandLineRunner {

    @Autowired
    private  BookRepository repository;
    . . .
}

我可以看到 BookRepository 接口(在此之后)只有在与 Application 类在同一个包中时才能注入:

I can see that the BookRepository interface (which follows here) can only be injected if it's in the same package as the Application class:

package test;
public interface BookRepository extends MongoRepository<Book, String> {

    public Book findByTitle(String title);
    public List<Book> findByType(String type);
    public List<Book> findByAuthor(String author);

}

是否有任何 Spring Boot 注释可以应用于我的类以便能够在另一个包中找到 BookRepository ?

Is there any Spring Boot annotation I can apply on my classes to be able to find the BookRepository in another package ?

推荐答案

使用 Spring @ComponentScan 注释与 SpringBoot @SpringBootApplication 并配置自定义基本包(您可以指定包名称列表或将使用其包的类列表),例如

Use a Spring @ComponentScan annotation alongside the SpringBoot @SpringBootApplication and configure a custom base package (you can either specify a list of package names or a list of classes whose package will be used), so for example

@SpringBootApplication
@ComponentScan(basePackages = {"otherpackage", "..."})
public class Application

@SpringBootApplication
@ComponentScan(basePackageClasses = {otherpackage.MyClass.class, ...})
public class Application

或自 Spring 1.3.0(2016年12月),可以直接写:

or since Spring 1.3.0 (Dec. 2016), you can directly write:

@SpringBootApplication(scanBasePackageClasses = {otherpackage.MyClass.class, ...})
public class Application

请注意,组件扫描将查找给定包内部和下方的类.

Note that component scan will find classes inside and below the given packages.

这篇关于Spring boot 在另一个包上找到自动装配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆