Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a HashMap to pick which interface (DAO) to autowire in SpringBoot?

I will try to be as detailed as possible. I have many DAO and my service needs to use one of them based on the key i get. For instance -

if(key.equals("abc") {
   obj = abcDAO.getOne(id);
} else if(key.equals("xyz") {
   obj = xyzDAO.getOne(id);
}

The object is of type parent class and abc, xyz.. are all child classes.

My idea is to create a Map<String, ParentCLass> to get the object just by passing the key instead of If-else so that it will be easy to add for further changes. In case it would've been a normal class, I wouldv'e initialized the map as

Map<String, ParentClass> map. 
map.put("abc", new Abc());

But since DAO are interfaces and require to be @Autowired for using them, I don't know how to proceed. I am a beginner. Any help appreciated.

like image 647
Leena Avatar asked Sep 10 '25 03:09

Leena


1 Answers

Spring is able to inject all beans with the same interface in a map if the map has String as key (will contain the bean names) and the interface as value.

public interface MyDao {
    
}

@Autowired
private Map<String, MyDao> daos;

EDIT: If you use Spring Data Repository, there is already a tagging Interface: Repository. You can use below code to inject all DAOs in one bean.

@Autowired
private Map<String, Repository> daos;

EDIT2: Example

public interface UserRepo extends JpaRepository<User, Long> { ... }

@Service
public class MyService {

    @Autowired
    private Map<String, Repository> daos;

    public List<User> findAll() {
        return daos.get("userRepo").findAll();
    }
}
like image 179
Cyril G. Avatar answered Sep 12 '25 17:09

Cyril G.