riorio
riorio

Reputation: 6836

Injecting a Spring bean that is from a dependency, but doesn't have @Bean annotation

My Spring Boot app has a new Zoo @Service class:

@RequiredArgsConstructor
@Service
public class Zoo{
    private final Cat cat;

I need to inject in the constructor a Cat class that I get from a legacy library that I import to the project via the pom:

    <dependency>
        <groupId>com.example</groupId>
        <artifactId>animals</artifactId>
    </dependency>

package com.example.animals
class Cat{..}

I can't change the code of the legacy animals package in order to add an annotation to the Cat class.

When I try to run the application I get this error:

Parameter 0 of constructor in com.example.zoo required a bean of type 'com.example.animals.cat' that could not be found

Is there a way to solve this?

Upvotes: 1

Views: 45

Answers (1)

Dina Bogdan
Dina Bogdan

Reputation: 4738

Yes, you can solve this by creating a @Configuration class where you define a Spring Bean which represents an instance of a Cat, like in the following example.

@Configuration
public class AppConfiguration {

  @Bean
  public Cat cat() {
    return new Cat();
  }
}

Upvotes: 2

Related Questions