3

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.

4

2 回答 2

0

@PostConstruct 似乎在使用@ManagedProperty 注入之前被调用,假设你有MyFaces 2.0,正如他们所说的here

确保您使用的是 Mojarra 2.1,因为它应该可以工作。

您可能会尝试调试以了解您的 init() 方法是在注入之前调用还是从未调用过。

于 2014-01-23T20:48:09.057 回答
-1

默认情况下,Spring 不会意识到 @PostConstruct 和 @PreDestroy 注释。要启用它,您必须注册CommonAnnotationBeanPostProcessor或指定<context:annotation-config />in bean 配置文件。

于 2014-01-23T20:13:59.347 回答