moretti.fabio
moretti.fabio

Reputation: 1138

Why I can't inject multiple instances of a bean?

I have two beans: one manage a single stock, other manage the movements between two stocks. So, in the MovStock bean I have:

@EJB
private Stock stock1;
@EJB
private Stock stock2;

[...]

public void setStocks(int idStock1, int idStock2) {
  stock1.loadStock(idStock1);
  stock2.loadStock(idStock2);
}

somewhere in my code, on another bean, I do:

@EJB
private MovStock movStock;

[...]

movStock.setStocks(10,20);

but it result in stock1 and stock2 to hold the same stock (20). Surely I'm doing something wrong, but what's the correct way to use multiple instance of the same bean that use @PersistenceContext, etc?

thank you

Upvotes: 1

Views: 612

Answers (1)

MGorgon
MGorgon

Reputation: 2607

Beans are container managed. So you don't have to worry about instances. Container will create new ones, when needed, but it will have this same state (if Statefull). It looks like Stock shouldn't be Enterprise Bean, but DTO. You shouldn't perform data operations on EJB's. EJB's should perform it on appropriate structures (DTO).

Upvotes: 2

Related Questions