5

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!

4

1 回答 1

13

@ManagedProperty是继承的,并且会以这种方式工作。也将@PostConstruct被继承,前提是子类本身没有@PostConstruct方法。即只能有一个。因此,如果子类本身具有@PostConstruct,则不会调用超类。

因此,如果您@PostConstruct在子类中覆盖 ,那么您需要显式调用超类的。

public class SuperBean {

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

}
@ManagedBean
public class SubBean extends SuperBean {

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

}

或者,提供子类必须实现的抽象方法(不带@PostConstruct!)。

public class SuperBean {

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

    public abstract void init();

}
@ManagedBean
public class SubBean extends SuperBean {

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

}
于 2012-10-29T11:54:31.190 回答