我的问题与此问题类似。我有一个BaseBean,它目前只有一个属性,注释为@ManagedProperty
.
但是,当我在命令按钮的操作方法中访问此继承的托管属性的 getter 时,它返回 null。我调试并确认基础 bean 构造函数被调用了两次 - 一次是在页面加载时,然后是在单击按钮时,如上述链接中所述。
我遵循了文章选择的答案以及这篇文章中提到的建议,但无济于事。
以下是我的代码:
public abstract class BaseBean
{
@ManagedProperty(value = "#{serviceLocator}")
private IServiceLocator serviceLocator;
public IServiceLocator getServiceLocator() {
return serviceLocator;
}
public void setServiceLocator(IServiceLocator serviceLocator) {
this.serviceLocator = serviceLocator;
}
}
@ManagedBean
@ViewScoped
public class RegistrationBean extends BaseBean implements Serializable
{
private static final long serialVersionUID = -6449858513581500971L;
private String userID;
private String password;
private String firstName;
private String lastName;
private String email;
private String addressLine1;
private String addressLine2;
private String city;
private String state;
private String pincode;
private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationBean.class);
/* getter / setters */
public String register()
{
String nextPage = null;
try {
RegistrationDetails userDetails = ModelBuilder.populateRegistrationData(this);
int registrationID = getServiceLocator().getUserService().registerUser(userDetails);
LOGGER.info("Registered user successfully. Registration ID - {}", registrationID);
nextPage = "success";
}
catch (RegistrationException e) {
LOGGER.error(e.getMessage());
}
return nextPage;
}
public void checkUserExists()
{
int regID = getServiceLocator().getUserService().findUser(getUserID());
if(regID > 0) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "User already exists !!", null);
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
}
为什么要在表单提交时再次调用构造函数???:/
checkUserExists()
即使在通过 ajax 对 userID 字段的 blur 事件调用的方法中,getter 也会返回 null 。
编辑:为 ServiceLocator 添加代码..
@ManagedBean
@ApplicationScoped
public class ServiceLocator implements IServiceLocator
{
private static final String USER_SERVICE = "userService";
private static final String MOVIE_SERVICE = "movieService";
@PostConstruct
public void init() {
final ServletContext sc = FacesUtils.getServletContext();
this.webAppContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
this.userService = (IUserService) webAppContext.getBean(USER_SERVICE);
this.movieService = (IMovieService) webAppContext.getBean(MOVIE_SERVICE);
}
private ApplicationContext webAppContext;
private IUserService userService;
private IMovieService movieService;
@Override
public IUserService getUserService() {
return userService;
}
@Override
public IMovieService getMovieService() {
return movieService;
}
}