Roman B
Roman B

Reputation: 81

Instantiate CDI beans dynamically or inject in non-cdi-beans

I'm new to CDI and hope someone can help me.

Well, let me explain problem:
I implemented a main bean which is called by JSF EL. This bean handles a list of objects. Just imagine something like List<Car>. These car objects are constructed in the @PostMethod method of the main bean.
Additionally I have some service classes e.g. CarServices which provides something like public static List<Car> getCarsOfBrand(Session session, Brand brand). Inside the service classes the Hibernate session is used to run a query and return the deserved list.
So, well... I wanted to get rid of passing the session object. So my plan was to inject it. I created a SessionScoped bean "PersistenceUnit" (may be that name is already preallocated, sorry for that...) with a method public Session getCurrentSession(). I simply want to inject this bean in all my Service classes to just call something like getCarsOfBrand(Brand brand). The problem is, that I can't inject CDI beans to non-beans. (Car is currently just a POJO). I tried to handle this by declaring car to an CDI bean, too, by adding a @SessionScoped. But the next problem was, that the Car objects were instantiated by me and not by the Container. I tried something like

@Produces
public Car createCar() {
     return new Car();
}

But that was also not successful: I thought this annotated method returns a proxy of car. But nothing happened. An injected field inside of car was still null and its @PostConstruct method was also never called.

So can you help me? What is the correct approach for injecting the current context (the session) to my service classes?

Thank you! :-)

Upvotes: 0

Views: 887

Answers (1)

Roman B
Roman B

Reputation: 81

So, I found a solution by myself! :-)

I annotate the service classes as @ApplicationScoped and inject whatever I need. The Car-Class uses the service but is no bean itself. For this I use DeltaSpike for the Injection when I instatiate the object:

public Car() {
  BeanProvider.injectFields(this);
}

Hope I could help someone in the future! :-)

Upvotes: 1

Related Questions