Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create two same beans differ in dependency

I have a service class which depends on a Repository Bean

@Service
public class SomeService{
   private Repo repoClass;
   @Autowired
   public SomeService(Repo repoClass){
      this.repoClass = repoClass;
   }
   //Methods
}

However I have two kinds of Repo

public class JdbcRepo implements Repo{
}

public class HibernateRepo implements Repo {
}

How do I make two beans of SomeService which one is injected with JdbcRepo and another is injected with HibernateRepo ?

like image 673
IllSc Avatar asked Sep 27 '22 02:09

IllSc


1 Answers

I have a simple solution here, please look into @Primary

I am assuming that you are using the annotation driven approach:

@Primary
@Repository(value = "jdbcRepo")
public class JdbcRepo implements Repo{
}

@Primary indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value.

@Repository(value = "hibernateRepo")
public class HibernateRepo implements Repo {
}

To Inject the dependency, you can use @Autowired with @Qualifier or only @Resource.

Now to inject JdbcRepo, you can just use @Autowired, because of the @Primary:

@Service
public class SomeService{
   @Autowired
   private Repo repoClass;
}  

To inject HibernateRepo, you have to use the @Qualifier

 @Service
    public class RandomService{
       @Autowired
       @Qualifier("hibernateRepo")
       private Repo repoClass;
    }  

For your concern two beans of SomeService which one is injected with JdbcRepo and another is injected with HibernateRepo, You can follow the same pattern for Service class that is followed for your Repository.

public interface SomeService{
}

@Primary
@Service(value = "jdbcService")
public class  JdbcService extends SomeService{
   @Autowired
   private Repo repo;
}

@Service(value = "hibernateService")
public class  HibernateService extends SomeService{
   @Autowired
   @Qualifier("hibernateRepo")
   private Repo repo;
}

To Inject SomeService with jdbcRepo:

@Autowired
private SomeService someService;

To Inject SomeService with HibernateRepo

@Autowired
@Qualifier("hibernateService")
private SomeService someService;

Please take into these Stackoverflow threads for further reference:

  • Autowiring two beans implementing same interface
  • Handling several implementations of one Spring bean/interface

I hope this helps you, feel free to comment!

like image 97
SyntaX Avatar answered Sep 29 '22 07:09

SyntaX