Kaushik G
Kaushik G

Reputation: 33

How to include Spring Components from a dependency in Maven

I have a spring boot project, "A". This contains a rest api get request called /helloworldA

I have created another spring boot project "B". I have added "A" as a dependency to "B". Now I was expecting /helloworldA to work when I run project "B". But it is not working

Upvotes: 1

Views: 2863

Answers (2)

Kaushik G
Kaushik G

Reputation: 33

Though @alexrolea answer is right for the issue, I also had another problem before this step.

Either maven's or gradle's spring boot plugin has 2 tasks:- jar task/execution - This will create a jar with all the dependencies. This can be used as a dependency for other projects. But this is not an executable jar. I mean that we cannot run this jar as "java -jar " bootJar task/execution - This runs after the jar task/execution. This will create a bootable jar. And the structure of the classes inside this jar is different. eg:- A class called com.eg.Config is located in /BOOT-INF/classes/com/eg/Config. Because of this modified structure, the other project will not be able to use this jar as dependency since the other project is unaware of this structure

My problem was that by default,

  1. jar and bootJar tasks create the jars with same filename. (ie) the jar from jar task is replaced by the jar from bootJar task
  2. In gradle, jar task is disabled by default. I enabled this with

    jar { enabled = true }

  3. I changed the name of the jar created from bootJar task with the following

    bootJar { classifier = 'boot' }

  4. Now followed the answer from @alexrolea.

Upvotes: 0

user10367961
user10367961

Reputation:

You should define a configuration in A.

@Configuration
@ComponentScan(/**scan all beans from A**/)
public class ConfigA {

}

Then, in B, you should import the configuration.

@Configuration
@Import(ConfigA.class)
public class ConfigB {

}

Now the beans from A should be detected by the component scan from B.

Upvotes: 4

Related Questions