This can be achieved with Spring's ObjectProvider<>
class which was introduced in Spring 4.3. See Spring's documentation for additional details.
The gist is to define the bean factory method for the object to be provided, inject the ObjectProvider<>
in your consumer and create new instances of the object to be provided.
public class Pair
{
private String left;
private String right;
public Pair(String left, String right)
{
this.left = left;
this.right = right;
}
public String getLeft()
{
return left;
}
public String getRight()
{
return right;
}
}
@Configuration
public class MyConfig
{
@Bean
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public Pair pair(String left, String right)
{
return new Pair(left, right);
}
}
@Component
public class MyConsumer
{
private ObjectProvider pairProvider;
@Autowired
public MyConsumer(ObjectProvider pairProvider)
{
this.pairProvider = pairProvider;
}
public void doSomethingWithPairs()
{
Pair pairOne = pairProvider.getObject("a", "b");
Pair pairTwo = pairProvider.getObject("z", "x");
}
}
NOTE: you don't actually implement the ObjectProvider<>
interface; Spring does that for you automagically. You just need to define the bean factory method.