Вопрос

I wanted to use @PostConstruct to initialize a bean in my webapp but I can't get it to work.

I've recreated the problem in a new project and it still won't work.

Am I missing something obvious here? As far as I can tell my init() method fulfills all the requirements listed in @PostConstruct API reference.

MyBean.java:

@ManagedBean
@RequestScoped
public class MyBean {
    @ManagedProperty(value="15")
    private int number = 10;

    @PostConstruct
    public void init(){
        number = 20;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }
}

number.xhtml:

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">

<h:head>
    <title>Simple JSF Facelets page</title>
</h:head>

<h:body>
    Number = #{myBean.number}
</h:body>

</html>

I would expect Number = 20 but I get Number = 15.

Это было полезно?

Решение

@PostConstruct seems to be called before the injection with @ManagedProperty, assuming you have MyFaces 2.0, as they say here.

Make sure you are using Mojarra 2.1 because it should work.

You might try to debug to know if your init() method is called before the injection, or never called.

Другие советы

By default, Spring will not aware of the @PostConstruct and @PreDestroy annotation. To enable it, you have to either register CommonAnnotationBeanPostProcessor or specify the <context:annotation-config /> in bean configuration file.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top