Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring boot @Autowired a bean from another module

My question is how can i add a package to my list of component to scan @ComponentScan(basePackages = {"io.swagger", "com.company.project", like add it here }), but this package is in another module in my project,

here is the structure of my project :

springbootProject (maven project)/

  module1(mavenProject, com.company.module1)
       pom1.xml

  module2(mavenProject, com.company.module2)
       pom2.xml

pom.xml

in module 2 i have my main (@SpringbootAplication) where i want to @Autowired myRepository witch is in module 1

so how can i add the path

like image 725
hamou amroun Avatar asked Apr 26 '18 13:04

hamou amroun


People also ask

Can we Autowire a bean?

The Spring framework enables automatic dependency injection. In other words, by declaring all the bean dependencies in a Spring configuration file, Spring container can autowire relationships between collaborating beans. This is called Spring bean autowiring.

What is difference between @bean and @autowire?

@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).

Can we use @autowired in pojo?

The beans can be wired via constructor or properties or setter method. For example, there are two POJO classes Customer and Person. The Customer class has a dependency on the Person. @Autowired annotation is optional for constructor based injection.

Does Spring @autowired inject beans by name or by type?

Spring @Autowired Annotation - Service ClassThe setter method will be used for spring autowiring byName and byType whereas constructor based injection will be used by constructor autowire attribute.


1 Answers

Import ModuleB on ModuleA, and you'll be able to use it.

Project
|__ Module A (com.test.a)
|__ Module B (com.test.b)

In pom.xml on ModuleA, add:

<dependency>
  <groupId>com.test</groupId>
  <artifactId>b</artifactId>
  <version>1.0</version>
</dependency>

Then you should be able to add:

@ComponentScan(basePackages = {"com.test.b"})
like image 190
Magd Kudama Avatar answered Sep 20 '22 15:09

Magd Kudama