mercredi 19 février 2020

Best practice to implement a spring bean

I have got a mapper class which does a complex mapping of one pojo to another. I made the mapper class a bean and wired it to the service class. I could have made the mapper class a static class as well but I preferred a bean because I felt it better in a testability point of view, I can test the service and mappers independently by mocking the mappers. Indeed it’s also possible to mock the static classes but I will have to use powermock or something similar. Another reason to choose a bean is that for certain mappers I had to use interfaces so that I can choose the mapper implementation based on certain data conditions.

This implementation as a bean has triggered a controversy in my team with suggestions to implement it as static class or to create new mapper objects every time. And we are trying to figure out what is the best solution. Are there any industry standards being followed. Are there any trade offs with the beans approach? Can it have any impact on the performance of my application? imagine that I have got a hundred such mappers. Below is a simple Skelton of how my service and mappers looks like.

@Service 
class CustomerService { @Autowired CustomerMapper customerMapper ...}

@Component 
class CustomerMapper { @Autowired CustomerContactMapper ..
}

interface CustomerContactMapper {}

@Component
class InternalCustomerContactMapper implements CustomerContactMapper {}

@Component
class ExternalCuatomerContactMapper implements CustomerContactMapper {}

Aucun commentaire:

Enregistrer un commentaire