John
John

Reputation: 1531

How to inject the same bean instance into multiple beans

I have an interesting problem I'm hoping you can help me with:

I have a bean called AContainer. It contains two beans, PartA and PartB. PartA and PartB need to share a bean which I'll call PartX.

My application will create multiple AContainers, each with their own PartA and PartB implementations. Each PartA and PartB pair, however, will need to share a PartX.

As I see it, if I make PartX a singleton, every PartA/PartB pair will share the same PartX (so I can't do that). If I make them prototypes, however, PartA and PartB will get their own individual PartX instances. Is there some third option that would allow me to set this up with Spring?

Upvotes: 0

Views: 1501

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85789

AFAIK Spring cannot handle custom scope injections for you. You will need to inject an instance of PartX manually for PartA and PartB in AContainer. One way to do is obtaining a single instance of PartX (prototype scoped) in the @PostConstruct of AContainer and then inject this instance in PartA and PartB:

@Component
@Scope("prototype")
public class AContainer {

    @Autowired
    private PartA partA;
    @Autowired
    private PartB partB;
    @Autowired
    private BeanFactory beanFactory;

    @PostConstruct
    public void init() {
        PartX partX = beanFactory.getBean("partX"); //name assumed
        partA.setPartX(partX);
        partB.setPartX(partX);
    }
    //rest of your code...
}

Upvotes: 3

Related Questions