1

What is the usual practice to instantiate domain objects? Suppose in an architecture like following:

@RestController
public class MyController implements ServletConfigAware {

        private ApplicationContext context;


        @RequestMapping(value="/getNewObject")
        public MyBusinessObject getANewObject(){

             MyService service = (MyService)context.getBean("myService);
             return service.getNewObject();

        } 

public class MyService {

        private ApplicationContext context;            

        public MyBusinessObject getNewObject(){

             return new MyBusinessObject();

                     vs

             (MyBusinessObject)context.getBean("myBusinessObject");

                     vs

             (MyBusinessObject)context.getBean("myBusinessObjectFactory").createNewMyBusinessObject();  //Factory is another class which returns a 'new' object
        }

}

public class MyBusinessObject { }

Am I using the spring IOC in intended way?

Anmol Gupta
  • 2,797
  • 9
  • 27
  • 43
  • The fact that you use Spring doesn't mean you have to use it for everything. Just create a new instance. – M. Deinum Oct 09 '15 at 07:24
  • But what happens when I update the instantiation logic of the object. Or change the implementation of an interface itself, suppose two classes implement an interface and I want to change the object of one class by the another implementation. In that case, It will be hard to change the code everywhere I have used 'new'. Isn't this the whole point of using a Factory instead of 'new'? And Spring is making such factories for us? – Anmol Gupta Oct 09 '15 at 07:48
  • 1
    Spring is for wiring your application classes, your entities aren't generally managed (nor do you want to) by Spring. If you want to use a factory use a factory but that doesn't mean that factory has to be a spring factory or managed by Spring. Using Spring doesn't mean you have to abandon all java practices. Spring isn't a golden hammer, silver bullet or whatever you like to solve all your problems (neither is Hibernate, JSF etc.). – M. Deinum Oct 09 '15 at 08:09
  • 1
    However using the context to grab a dependency is never a good idea, for that use dependency injection. – M. Deinum Oct 09 '15 at 08:25
  • I get that..Thanks!..Where should I draw the line? When application starts up, spring makes at least the controllers. But Spring will also need to make Services (singleton) which will be injected into controllers so that they make services do their work. I can keep my domain objects out of spring by making factory services for them. But then, those factories will be injected into Services which are being instantiated by Spring. So my factories will need to be instantiated by Spring as well. Will this be a good design? – Anmol Gupta Oct 09 '15 at 09:01

0 Answers0