Riduidel
Riduidel

Reputation: 22308

How does the @Produces work in JavaEE context?

From the CDI tutorial, i've discovered various examples and want to use them to inject some objects into an EJB (namely, I want to inject a Neo4J connector GraphDatabaseService). So, I have a target EJB :

@Stateless
public class Neo4JEJB implements Neo4JEJBInterface{

private @Inject @Named("the bidule") String bidule = "no bidule injected";
}

And a producer class containing a producer method

public class Producer {
public @Produces @Named("the bidule") String createBidulateur() {
    return "the bidule that should always work";
}
}

But, so far, i've been unable to see my bidule field having the correct value.

Is there something i'm doing wrong ?

Upvotes: 2

Views: 4238

Answers (1)

Gyan
Gyan

Reputation: 12410

Firstly, you are using @Named like the old Seam @Name. These two annotations have two different purposes. In CDI, @Named is only used to provide a name that can be used to reference the bean from within a facelet. On injection, a bean is identified by it's type and optionally using a qualifier. Since you are injecting a String, a qualifier is most likely necessary. You can create a qualifier annotation as described here and annotate your producer and injection point with it:

If you created the qualifier @Bidule

@Stateless
public class Neo4JEJB implements Neo4JEJBInterface{

    private @Inject @Bidule String bidule = "no bidule injected";
}

public class Producer {
    public @Produces @Bidule String createBidulateur() {
        return "the bidule that should always work";
    }
}

Also, I think (but am not sure) the bean that contains the producer method needs to be scoped (see here).

Upvotes: 4

Related Questions