我想在我的webapp中使用@PostConstruct初始化一个bean,但是我无法让它工作。
我在一个新的项目中重新创造了这个问题,但它仍然行不通。
我是不是漏掉了什么明显的东西?据我所知,我的init()方法满足了@PostConstruct API引用中列出的所有需求。
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>我期待Number = 20,但我得到了Number = 15。
发布于 2014-01-23 20:48:09
@PostConstruct似乎是在使用@ManagedProperty的注入之前调用的,假设您拥有MyFaces 2.0,就像人们所说的here。
确保您使用的是mojarra2.1,因为它应该可以工作。
您可以尝试调试,以了解init()方法是在注入之前调用的,还是从未调用过。
发布于 2014-01-23 20:13:59
默认情况下,Spring将不知道@PostConstruct和@PreDestroy注释。要启用它,您必须注册CommonAnnotationBeanPostProcessor或在bean配置文件中指定<context:annotation-config />。
https://stackoverflow.com/questions/21318227
复制相似问题