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;
}
}
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:Alternatively, to achieve the same results we can use the @Lookup annotation, for example: