Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can @ManagedPropery and @PostConstruct be placed in a base class?

I'm using a hierarchy of classes and what I would optimally try to do is have @ManagedBean's that inherit a class that have @ManagedProperty members and @PostConstruct methods.

Specifically, will this work? :

public class A {

    @ManagedProperty
    private C c;

    @PostConstruct
    public void init() {
        // Do some initialization stuff
    }

    public C getC() {
        return c;
    }

    public void setC(C c) {
        this.c = c;
    }
}

@ManagedBean
@SessionScoped
public class B extends A {
    // Content...
}

Thanks in Advance!

like image 968
Ben Avatar asked Oct 29 '12 08:10

Ben


1 Answers

The @ManagedProperty is inherited and will just work that way. The @PostConstruct will also be inherited, provided that the subclass itself doesn't have a @PostConstruct method. There can namely be only one. So if the subclass itself has a @PostConstruct, then the superclass' one won't be invoked.

So if you override the @PostConstruct in the subclass, then you'd need to explicitly invoke the superclass' one.

public class SuperBean {

    @PostConstruct
    public void init() {
        // ...
    }

}
@ManagedBean
public class SubBean extends SuperBean {

    @PostConstruct
    public void init() {
        super.init();
        // ...
    }

}

Alternatively, provide an abstract method which the subclass must implement (without @PostConstruct!).

public class SuperBean {

    @PostConstruct
    public void superInit() {
        // ...
        init();
    }

    public abstract void init();

}
@ManagedBean
public class SubBean extends SuperBean {

    @Override
    public void init() {
        // ...
    }

}
like image 96
BalusC Avatar answered Sep 30 '22 03:09

BalusC