Search code examples
javaspringspring-annotations

Field required a bean of type ... that could not be found


In my Spring project I have an interface:

public interface MyIntefrace {

    void myMethod(String myParam);
}

and I have a class that implements it:

@Component
@Profile("prod")
public class MyImplementationClass implements MyInterface {
    ...

In my other class, I'm using this object as follows:

@Autowired
MyInterface myinterface;

...

myinterface.myMethod(someParam);

And it throws me an error:

Field myinterface in mypackage required a bean of type ... that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

Consider defining a bean of type '...' in your configuration

I tried to add @Service annotation above MyInterface but that didn't help. What else can I do?


Solution

  • Make sure the prod profile is enable such as through :

    1. JVM property :

      -Dspring.profiles.active=prod

    2. Or environment variable:

      export spring_profiles_active=prod

    3. Or programmatically when creating ApplicationContext:

      AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
      //...........
      ctx.getEnvironment().setActiveProfiles("prod");
      ctx.refresh();