dvas0004 / NerdNotes

A collection of notes: things I'd like to remember while reading technical articles, technical questions I couldn't answer, and so on.
12 stars 0 forks source link

Spring ObjectFactory / @Lookup #59

Open dvas0004 opened 5 years ago

dvas0004 commented 5 years ago

It is sometimes desirable to allow a Singleton-scoped object to produce Prototype-scoped objects. For example, in Spring, a lookup service (which is singleton scoped) - when called multiple times for different lookups - would need to return a unique result for each call (which is therefore prototype-scoped).

This is where ObjectFactory comes in. It allows you to dynamically build objects with potentially different scopes, for example:

// this is a component describing some sort of result to be returned
// from the lookup service defined below
@Component
@Scope("prototype")
class Result {
   // note that "Result" is prototype-scoped
  [...]
}

// this is a lookup service, which by default is given a singleton scope by spring
@Component
class MyLookupService {

   // here we inject an ObjectFactory which references the "Result" component
   @Autowired
   ObjectFactor<Result> resultFactory;

   @Autowired
   Result result

   Result getResult() {

        // note the explicit call to "getObject". This will return a prototype scoped "Result" object
        result = resultFactory.getObject()
        return result;

   }
}

Alternatively, to achieve the same results we can use the @Lookup annotation, for example:

@Component
class MyLookupService {

   @Autowired
   Result result

   @Lookup
   Result getResult() {

        result = Result()
        return result;

   }
}