samedi 10 novembre 2018

Java Spring design: all in one component?

Sometimes Spring components may look like this:

@Service
public final class SomeService {
    @Autowired
    private SomeService2 someService2;
    @Autowired
    private SomeService3 someService3;
    @Autowired
    private SomeService4 someService4;
    // … and many other services
    @Autowired
    private SomeDao someDao;
    @Autowired
    private SomeDao2 someDao2;
    @Autowired
    private SomeDao3 someDao3;
    // … and many other DAOs

}

In other words Spring components have plenty services and DAOs that are mostly repeated in other Spring components. IMHO it has the following drawbacks:

  • Unnecessary (boilerplate) code for autowiring most of the same components
  • Sometimes circular references may occur

What about to use all-in-one component that combine, say, all services or all DAOs:

@Service
public final class AllServices {
    @Autowired
    private SomeService2 someService2;
    @Autowired
    private SomeService3 someService3;
    @Autowired
    private SomeService4 someService4;
    // … and many other services

    // get methods to get some service
    public someService getSomeService(){};

and inject it into other components:

@Service
public final class SomeService {
    @Autowired
    private AllServices serv;
    @Autowired
    private AllDaos daos;
    @Autowired
    private Environment env;

// inside some code
…
serv.getSomeService().processData();

IMHO it will look more succinct without circular references issues…

What pros and cons of this approach?

Aucun commentaire:

Enregistrer un commentaire