我遇到的问题是我有一堂课,看起来像这样
@Component
@RequestScope
public class TableModel{
private Integer tableField1;
...
//other properties, getters and setters here
}
Mybatis返回来自映射到该对象的查询的结果,我希望将这个对象的结果复制到另一个类中的Spring bean中,如下所示:
public class MyClass {
TableModel model
@Autowired
MyClass(TableModel model) {
this.model = model;
//...
}
//some code
TableModel result = MyMapperInterface.selectFromTable();
//Here, result.tableField1 is not 0 or null
BeanUtils.copyProperties(result, model);
//After copyProperties(), model.tableField1 is still null
//...
}
但是,在
BeanUtils.copyProperties()
调用之后,model
中的属性仍然为空。我仔细检查过,没有使用copyProperties的Apache Commons版本,而是使用了BeanUtils的Spring版本。有什么问题 最佳答案
@RequestScope
意味着您为每个请求获得一个不同的实例。从语义上讲,这与将其作为构造函数参数传递不匹配(意味着它已为该bean的所有用户共享)。
即使这样,Spring也会通过为您的TableModel
注入代理来尝试根据您的请求上下文神奇地切换它,从而为您实现这一目标。可能发生的情况是您的基础实例不相同。
通常避免使用请求范围的bean。不要对每个请求的数据使用注入;使用方法参数代替。 (而且我建议使用MapStruct而不是BeanUtils,因为它既快捷又安全。)