JSF 2 : Is it possible to inherit @ManagedBean?

后端 未结 2 1303
一向
一向 2020-12-20 16:58

I have a Bean ,with a @ManagedBean annotation, defined like this :


@ManagedBean
@SessionScoped
public class Bean implements Serializable {

            


        
相关标签:
2条回答
  • 2020-12-20 17:31

    do you need BaseBean to be a managed bean? Since you name it BaseBean, I assume that this bean hold commonality between all your other managed bean. If so then it should not contain @ManagedBean annotation. Do this

    public abstract BaseBean{
        //...
    }
    

    Then inside your managed bean

    @ManagedBean
    @RequestScoped
    public class FooBean extends BaseBean{
        //...
    }
    
    0 讨论(0)
  • 2020-12-20 17:38

    The point Alex is trying to make is that you're confusing classes with instances. This is a classic (pun intended) OOP mistake.

    The @ManagedBean annotation does not work on classes per-se. It works on instances of such classes, defining an instance that is managed.

    If your bean is defined like this:

    @ManagedBean
    @SessionScoped
    public class MyBean implements Serializable {
    
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
    }
    

    Then it means you have a session-scoped instance, called myBean (or whatever you want to name it).

    Therefore, all classes that are subclasses of the MyBean class are not managed by default. Furthermore, how does JSF recognize where you're using the subclasses? If so, what names are you giving to those instances? (Because you have to give them some name, otherwise, how would JSF manage them?)

    So, let's say you have another class:

    Class MyOtherClass {
        private MyBean myBeanObject; // myBeanObject isn't managed. 
    }
    

    what happens to the @PostConstruct and all the other annotations you used? Nothing. If you created the instance of MyBean, then it's YOU who manages it, not JavaServerFaces. So it's not really a managed bean, just a common object that you use.

    However, things change completely when you do this:

    @ManagedBean
    @SessionScoped
    Class MyOtherClassBean {
        @ManagedProperty("#{myBean}")
        private MyBean myBeanObject;
    
        public void setMyBeanObject(...) { ... }
        public MyBeanClass getMyBeanObject() { ... }
    }
    

    Then again, what is managed is not the class, but the instance of the class. Having a ManagedBean means that you only have one instance of that bean (per scope, that is).

    0 讨论(0)
提交回复
热议问题