Thomas
Thomas

Reputation: 41

How do I outject an object for CDI / Weld

I think it is a pretty basic question, but I haven´t found a solution yet. How would I "outject" an object, which I would later like to have as an object to be injected.

Let´s say, we have ServiceA, which creates an Object

@Stateless
public class ServiceA {

  public void createObject() {

      MyObject myObject = callSomeService();
      ---> now put myObject into the session
  }
}

And another Service B should be able to use this object:

@Stateless
public class ServiceB {

  //should be available here
  @Inject
  private MyObject myObject

}

How would I do that? Thanks for your help!

Upvotes: 0

Views: 271

Answers (2)

John Ament
John Ament

Reputation: 11733

Specifically, the producer method you need will look like this:

@Produces
@SessionScoped
public MyObject createSessionObject() {
    return callSomeService();
}

This will be called once for the session, the first time accessed.

Upvotes: 3

user201891
user201891

Reputation:

You will probably need to use a Producer method.

A producer method can allow you to select a bean implementation at runtime, instead of at development time or deployment time. ~ Java EE 6 Tutorial

You can find examples of how to use Producer methods online. This tutorial seems useful.

Similar question:

Upvotes: 1

Related Questions