JavaEE:关于设计的问题
我有一个JSF页面,它将创建一个新的JavaEE:关于设计的问题,java,jsf,jakarta-ee,Java,Jsf,Jakarta Ee,我有一个JSF页面,它将创建一个新的注释。我将该页面的托管bean设置为RequestScopedmanagedbean @ManagedBean(name="PostComment") @RequestScoped public class PostComment { private Comment comment = null; @ManagedProperty(value="#{A}") private A a; //A is a ViewScoped Bean
注释
。我将该页面的托管bean设置为RequestScoped
managedbean
@ManagedBean(name="PostComment")
@RequestScoped
public class PostComment {
private Comment comment = null;
@ManagedProperty(value="#{A}")
private A a; //A is a ViewScoped Bean
@ManagedProperty(value="#{B}")
private B b; //B is a ViewScoped Bean
@PostConstruct
public void init(){
comment = new Comment();
}
// setters and getters for comment and all the managed property variable
...
public void postComment(String location){
//persist the new comment
...
if(location.equals("A")){
//update the comment list on page A
a.updateListOnA();
}else if(location.equals("B")){
//update the comment list on page B
b.updateListOnB();
}
}
}
从上面的代码中可以看到,2个ViewScope bean A和B都将使用方法postComment()
。两者都将组件绑定到属性comment
,因此都将从beanPostComment
访问gettergetComment()
。我现在遇到的问题是,如果我在A上,A的构造函数将被加载,但它也将加载bean B的构造函数(因为使用ManagedProperty的bean注入)。这使我的页面加载速度慢了一倍。解决这个问题的最好办法是什么
编辑
我一直在思考的一种方法是:创建两个不同的RequestedScoped bean,
PostAComment
和PostBComment
,然后PostAComment
将不再需要注入beanB
,因此不会加载B
构造函数。现在将实现这一点,直到有人能给我指出一个更好的解决方案,我认为你应该删除a
和B
bean并创建一个服务,它将根据位置字符串保留注释。PostComment
bean应该调用这个方法
在任何页面上发布评论后,应刷新该页面,并从数据库中再次加载评论
编辑:
服务只是一个时髦词,它可以是会话bean,也可以只是一个简单的java类:
public class CommentService {
public void comment(Comment comment, String location) {
//persist the comment
}
//other methods like loading the comments from db
}
重构后,原始bean应如下所示:
@ManagedBean(name="PostComment")
@RequestScoped
public class PostComment {
private Comment comment = null;
private CommentService commentService;
@PostConstruct
public void init(){
comment = new Comment();
commentSetvice = new CommentService();
}
// setters and getters for comment
...
public void postComment(String location){
commentService.comment(comment, location);
}
}
我不知道A和B包含什么,但这段代码足以添加注释。要显示注释,您应该创建其他bean,从数据库加载注释。我对该服务不太熟悉。你觉得你能给我一些示例代码吗?另外,如果我改为服务,我还能保留bean A和B中的逻辑吗?在这两个bean中有很多方法