Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot find autowired on another package

Tags:

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 ?

like image 317
user2824073 Avatar asked May 24 '15 15:05

user2824073


People also ask

How do I scan a Spring boot to another package?

With Spring, we use the @ComponentScan annotation along with the @Configuration annotation to specify the packages that we want to be scanned. @ComponentScan without arguments tells Spring to scan the current package and all of its sub-packages.

How do I automatically detect Autowiring internally?

autodetect The autodetect mode uses two other modes for autowiring – constructor and byType. It first tries to autowire via the constructor mode and if it fails, it uses the byType mode for autowiring. It works in Spring 2.0 and 2.5 but is deprecated from Spring 3.0 onwards.

Can you Autowire byType when more than one bean with the same type exists?

Autowiring using property type. Allows a property to be autowired if exactly one bean of property type exists in the container. If more than one exists, it's a fatal exception is thrown, which indicates that you may not used byType autowiring for that bean.

What is the difference between @bean and @autowired?

@Bean is just for the metadata definition to create the bean(equivalent to tag). @Autowired is to inject the dependancy into a bean(equivalent to ref XML tag/attribute).


1 Answers

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.

like image 100
Lukas Hinsch Avatar answered Sep 30 '22 10:09

Lukas Hinsch