LookIntoEast
LookIntoEast

Reputation: 8798

Spring inject interface implementation

I'd like to use lombok to inject a class implemented from a interface like below:

@RequiredArgsConstructor(onConstructor = @_(@Inject))
public class className {
    @NonNull
    private final ClassA1 a1 implements ClassA;
    ...
}

But obviously this is not working, so what's the correct way to do this?

=================

edit: Or should I do this way?

public class className {
        private ClassA a1;
        public className(A1 a1) {
        this.a1 = a1; }
    }

=================== Here's the code after taking advice from Mykhailo Moskura:

@Component
@RequiredArgsConstructor(onConstructor = @_(@Inject))
public class C {
     @NonNull
     private A b;
     public someFunction() {
        b.method();
     }
}

Here A is the interface, while b is Class implementing A with camelcase name. And using lombok I injected b, and now call some method of b in some function. However I realized b.method still points to the interface A, but not B.

Upvotes: 2

Views: 3068

Answers (1)

Mykhailo Moskura
Mykhailo Moskura

Reputation: 2211

@NonNull is not required Lombok will generate a constructor with fields that are marked as final or @NonNull You can autowire just declaring the interface type and giving the implementation class name in camel case starting from lower case. Also you need to declare your implementation as bran and the class in which you are injecting it too. @Inject is java ee CDI dependency. @Autowired is spring specific. Spring supports both but it says to use @Autowired Here is an example:

public interface A{
}

@Component
public class B implements A{
}

@Component
public class C {
  private A a;
@Autowired
  public C(A a){
   this.a = a;  
}
}

Lombok sample:

 @RequiredArgsConstructor
   @Component
    public class C {
      //Here it will inject the implementation of A interface with name of implementation (As we have name of impl B we declare field as b , if HelloBeanImpl then helloBeanImpl
     private A b;
    }

But if you have many implementations of one interface you can use @Qualifier with name of bean or the above sample with lombok where A b where b is the name of implementation

Upvotes: 4

Related Questions