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 ?
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.
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.
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.
@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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With