Y0gesh Gupta
Y0gesh Gupta

Reputation: 2204

Spring Config Bean Injection with generic

I have a generic interface-

Interface A<T1,T2>{

public T1 getSome(T2 input);

}

I have a wrapper class-

Class B implements A<C,D>{

@Override
public D getSome(C input){

  // Do something
  return D;
}}

Now I have a spring config class

@Configuration
public Class BConfig{

@Bean
public A b(){
  return new b();
}}

Now I have an AppConfig class

@Configuration
Class AppConfig(){

@Inject
private A b

public App app(){
  return new App(b);
}}

My App class looks like-

public Class App{
  A b;
  public App(A b){
    this.b=b;}
  public void doSome(){
    C c=new C();
    D d=b.getSome(c);
  }
}

Now in my App class do I need to initialize B using-

A<C,D> b; 

or

A b;

Since the the bean injection will inject the implementation of A which is B in spring config. I dont want to specify the generic type as this will kind of defeat the purpose of using the generics slightly.

Upvotes: 0

Views: 149

Answers (1)

Mykhailo Moskura
Mykhailo Moskura

Reputation: 2211

Spring autowires beans by type , qualifier and by name.

It depends how you want to use them. In case you define them without generics you will work with java.lang.object which means you will cast to some type when you need to use those logic in some classes

With generics you would not have such problem .

Here is an example :

@Configuration
public class BConfig{

 @Bean
 public A<C,D> b(){
  return new B();
 }
}

@Component 
public class E {
 @Autowired
 private A<C,D> b; 
}

Upvotes: 1

Related Questions