Spring boot find autowired on another package

2020-08-09 06:08发布

问题:

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;
    . . .
}

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);

}

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

回答1:

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

or

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

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.



回答2:

Good to verify the scopes of classes kept in different packages by using @ComponentScan annotation in Spring boot startup custom class.

Also add @Component in modal classes being used to allow framework accessing the classes.

Example is kept at http://www.javarticles.com/2016/01/spring-componentscan-annotation-example.html



标签: spring-boot