Search code examples
javaspringspring-bootmaventomcat

Import Beans from custom library to springbootAplication from a different project


I have been struggling trying to create a library with the use of the beans from it to a different project and call a method from it

Stack is: Springboot 2.3.4 and Java 1.8 with Maven

The projects are:

  • Project A : the main project
  • Project B: custom library that will have 1 method to be invoked

This is the structure of Project B:

enter image description here

CoffeOrderService class:

package com.codecademy.coffeeorders.service;
@Service("coffeOrdersService")
public class CoffeeOrdersService {

@Autowired
@Qualifier("CoffeOrderRepository")
public CoffeeOrderRepository coffeeOrderRepository;

public  CoffeeOrdersService() {
}


public boolean checkRequest(String action){
    /*
    --Stuff doesnt matter
     */
    return true;
}
}

Repository:

package com.codecademy.coffeeorders.repository;
public interface CoffeeOrderRepository extends JpaRepository<CoffeeOrder, Long> {
}

CoffeOrdersAplication

@SpringBootApplication
public class CoffeeOrdersApplication {

public static void main(String[] args) {
    SpringApplication.run(CoffeeOrdersApplication.class, args);
}}

For the SpringbootAplication of project b i have been trying to define ComponentScan to fetch the repository but didnt work for me.

When i add project B as a library with maven to the project A and try to launch it (using Apache Tomcat) i get error like: no such bean definition exception with the Reposiror CoffeOrderRepository that is an attribute to CoffeeOrdersService.

I even tried to define the Bean CoffeOrderService manually inside the Project B springbootAplication context with @Bean notacion but always get the error for the Repository dependency of project B.

In case you need more info about the projects let me know.

Thanks in advance


Solution

  • First add the Project B as dependency in maven of main Project then in your Project A(Main project) try adding below componentScan in the Main class:

    @ComponentScan(basePackages = {"com.codecademy.coffeeorders.*"})