Cant access property of managed bean from another managed bean

后端 未结 1 1478
予麋鹿
予麋鹿 2020-12-22 04:39

I want to access the property of a @SessionScoped bean in another bean using @ManagedProperty. In short, I want to access the name property of firs

相关标签:
1条回答
  • 2020-12-22 05:00

    It's not possible to access an injected dependency in the constructor. You're basically expecting that Java is able to do something like this:

    SecondBean secondBean; // Declare.
    secondBean.firstBean = new FirstBean(); // Inject.
    secondBean = new SecondBean(); // Construct.
    

    It's absolutely not possible to set an instance variable if the instance is not constructed yet. Instead, it works as follows:

    SecondBean secondBean; // Declare.
    secondBean = new SecondBean(); // Construct.
    secondBean.firstBean = new FirstBean(); // Inject.
    

    Then, in order to perform business actions based on injected dependencies, use a method annotated with @PostConstruct. It will be invoked by the dependency injection manager directly after construction and dependency injection.

    So, just replace

    public SecondBean() {
        System.out.println(firstBean.getName());
    }
    

    by

    @PostConstruct
    public void init() { // Note: method name is fully to your choice.
        System.out.println(firstBean.getName());
    }
    
    0 讨论(0)
提交回复
热议问题