Tom T
Tom T

Reputation: 273

Trouble with injection

I have a problem where injection fails on first try but not on second. My app is laid out like this (this is a Java EE application using Maven in Eclipse):

@Stateful
@Named("myBean")
@SessionScoped

public class MyBean implements Serializable {

@Inject
private User user;
...

@PostConstruct
public String init() {
.. do some general tasks, no issues here.
}

public String initApplication() { // this gets called on page load
   String userId = user.getId(); 
...
}

....  in another class...

@Produces
@SessionScoped
@Named("user")
public User produceUser() {
  // code to create user is here
}

Symptom: I start the browser, clear the cache, start the application. I get a null on user the @Produces method is never called. I call the same URL again to start the application, and then it works.

Upvotes: 2

Views: 708

Answers (1)

Adam Waldenberg
Adam Waldenberg

Reputation: 2321

Named injection can be a little unstable on some EE servers when used in combination with @Produces. Not only this, but it actually creates a completely separate instance with ambiguity. So if you have a User bean defined in session scope somewhere else they are considered two different sources of injection. Maybe that's what's happening and it's picking up the second one when you reload?

What happens if you move away from the @Produces (remove produceUser()) and instead do;

@Named
@SessionScoped
public class User implements Serializable {
    @PostConstruct
    private init() {
        /* Do what you did in the producer method here */
    }
}

That should really work - otherwise something is seriously wrong.

Upvotes: 2

Related Questions