注入问题

huangapple go评论133阅读模式
英文:

Trouble with injection

问题

我有一个问题,注入在第一次尝试时失败,但在第二次尝试时不会失败。我的应用程序布局如下(这是一个在Eclipse中使用Maven的Java EE应用程序):

@Stateful
@Named("myBean")
@SessionScoped
public class MyBean implements Serializable {

    @Inject
    private User user;
    ...

    @PostConstruct
    public String init() {
        // 做一些一般性任务,在这里没有问题。
    }

    public String initApplication() { // 这在页面加载时被调用
        String userId = user.getId();
        ...
    }

    // 另一个类中...
    @Produces
    @SessionScoped
    @Named("user")
    public User produceUser() {
        // 创建用户的代码在这里
    }
}

症状:我启动浏览器,清除缓存,启动应用程序。user 为 null,@Produces 方法从未被调用。我再次调用相同的URL以启动应用程序,然后它正常工作。

英文:

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.

答案1

得分: 2

命名注入在某些EE服务器上与@Produces组合使用时可能不太稳定。不仅如此,它实际上会创建一个完全独立的实例,存在歧义。因此,如果您在其他地方的会话范围中定义了一个名为User的bean,它们被视为两个不同的注入源。也许这就是发生的情况,当重新加载时它会选择第二个?

如果您移出@Produces(删除produceUser())并改为这样做会发生什么:

@Named
@SessionScoped
public class User implements Serializable {
    @PostConstruct
    private init() {
        /* 在这里执行您在生产者方法中所做的操作 */
    }
}

这应该可以正常工作 - 否则可能出现严重问题。

英文:

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.

huangapple
  • 本文由 发表于 2020年8月4日 01:36:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63234335.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定