Home > OS >  Consider defining a bean of type '[3rd party dependency]' in your configuration
Consider defining a bean of type '[3rd party dependency]' in your configuration

Time:10-17

I have a Maven project which has approximately the following structure:

project
|--.mvn
|--target
|--backend
|  |--main
|  |  |--src/main/java/com.project
|  |  |  |--controllers
|  |  |  |  |RestController.java
|  |  |  |ProjectApplicationMain.java
|  |  |--src/main/resources
|  |  |  |application.yaml
|  |  |--target
|  |  |pom.xml
|pom.xml

Dependencies are defined in the pom.xml file that is in the root directory of the whole project and pom.xml files of the sub-modules simply use

<relativePath>../../pom.xml</relativePath>

I wish to use dependencies defined in the pom.xml in the RestController.java class, but I am getting the following error when trying to compile the code:

Parameter 0 of constructor in com.project.controllers.RestController required a bean of type 'aClassFromTheDependency' that could not be found.

Action:
Consider defining a bean of type 'aClassFromTheDependency' in your configuration.

The RestController.java class looks approximately as follows:

@RestController
@RequestMapping("/api")
public class RestController {
  private final AClassFromTheDependency aClassFromTheDependency;

@Autowired
public RestController(AClassFromTheDependency aClassFromTheDependency) {
    this.aClassFromTheDependency = aClassFromTheDependency;
  }

  @GetMapping("/make-request")
  public ResponseDTO someApi() {
    final ResponseDTO response = new ResponseDTO();
    response.setResponse(aClassFromTheDependency.aMethodFromTheDependency());
    return response;
  }
}

Additionally, the ProjectApplicationMain.java looks like this:

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
@EnableConfigurationProperties({
  FileStorageProperties.class
})
@ComponentScan(basePackages = {"com.project"})
@EnableJpaRepositories(basePackages = {"com.project"})
@EntityScan(basePackages = {"com.project"})
@EnableCaching
public class ProjectApplicationMain {

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

Any ideas what seems to be the case here that I simply cannot create an instance of the dependency's class and use its methods?

CodePudding user response:

In order to create a bean defined in a third party library (any other class that is not your custom one, like standard classes from the JDK) you can create a method annotated with @Bean inside your configuration class.

@Configuration
public class MyConfig {
    @Bean
    AClassFromTheDependency aClassFromTheDependency() {
        
        return AClassFromTheDependency.getInstance();
    }
}

Note

  • That's not the best practice to search components in each and every package of your project.

  • You can't place annotation on the third party classes, hence such problem can't be resolved via @ComponentScan.

  • Related