Reputation: 3243
I have a class
public class Test {
@Autowired
private Testing abc;
public Testing getTesting() {
return abc;
}
}
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class Testing {
private int i;
}
Everytime I manually create class Test using the autowire capable bean factory, i expect an instance of Testing to be created.
However today i was introduced to a new concept of javax.inject.Provider
public class Test {
@Autowired
private Provider<Testing> abc;
public Testing getTesting() {
return abc.get();
}
}
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class Testing {
private int i;
//transactional methods
}
What benefit does it provides?
Upvotes: 1
Views: 937
Reputation: 41965
- retrieving multiple instances.
- lazy or optional retrieval of an instance.
- breaking circular dependencies.
- abstracting scope so you can look up an instance in a smaller scope from an instance in a containing scope.
From Java EE Documentation:Provider
UPDATE:
Java EE Documentation: Inject Annotation discusses how circular dependencies in classes can be broken using Provider
.
A conservative injector might detect the circular dependency at build time and generate an error, at which point the programmer could break the circular dependency by injecting Provider or Provider instead of A or B respectively.
Upvotes: 2