2

I have two projects A and B. Both are built with Maven, and project A has a Maven dependency to project B. Both project have a class with @Configuration annotation where I define @Beans.

I have beans in project A, from both projects. If I use the @Autowired annotation in project A of a bean that is defined in same project, the autowiring works. However, if I use the @Autowired annotation in project A of a bean from project B, I will get an exception.

What does this mean? How can I autowire a bean in project A, that is defined in project B?

user1340582
  • 19,151
  • 35
  • 115
  • 171
  • what is the exception? Do you have project B listed as a dependency in your project A pom file? Are the project B jar files in the class path for project A? – obi1 Feb 09 '16 at 20:23

1 Answers1

7

This is normally an issue with the base classpath on ComponentScan.

If you for example have the following base packages

com.myproject.a

and

com.myproject.b

in your project A and B respectively, and you're using SpringBoot with the main class

package com.myproject.a

@Configuration 
@EnableAutoConfiguration 
@ComponentScan
class MyApp {
    // Some public static void main ... 
}

it will only find your classes in the package com.myproject.a and it's children.

To solve this issue you must enhance the @ComponentScan in a way that it scans both package structures, eg.

package com.myproject.a

@Configuration 
@EnableAutoConfiguration 
@ComponentScan(basePackages = {"com.myproject.a", "com.myproject.b"} 
// or basePackages = "com.myproject" in this example
class MyApp {
    // Some public static void main ... 
}
Peter
  • 783
  • 4
  • 14
  • Hmm but the problem is that I have separate @Configuration classes and beans in both projects A and B respectively. So the beans should be scanned by both project scanners. The problem is when I try to Autowire a bean from project B in project A, then it says it cannot find the bean. In your solution, I suppose I would not define any beans in project B, only in project A? – user1340582 Feb 09 '16 at 21:15
  • Hi, sorry for being unclear about this. You have one project which initiates the scan process. In your case Project A. This initial scanner needs to know about the package-trees to be scanned. This brings him into the place to find all @Configuration classes in the package-trees. I hope this clearifies it a little bit more – Peter Feb 10 '16 at 07:35
  • Thanks for clarification :) I thought there were two separate scanners involved, but now I get it. Thanks! – user1340582 Feb 10 '16 at 08:47
  • In my case Project A is unaware of Project B, so how to handle this situation. Project is Provider and Project B is consumer, so the consumer can be anybody. – Lakshay Sharma Jun 30 '21 at 14:19