英文:
How do I tell Spring to exclude binding an object property?
问题
我有一个Spring控制器方法,有两个对象参数:
@GetMapping
public List<Car> getCars(BlueBookCar blueBookCar, AutoTraderCar autoTraderCar)
BlueBookCar
和AutoTraderCar
都有一个名为id
的字段。我希望在HTTP GET请求中,查询参数名id
只绑定到BlueBookCar
实例。
例如,以下请求:
http://localhost/cars?id=123
应该导致blueBookCar
具有id
等于123。而autoTraderCar
的id应该为null。但是,Spring设置了两个对象的id
都为123。
我该如何告诉Spring排除绑定autoTraderCar
的id
?其他与查询参数名匹配的autoTraderCar
字段应该设置(如Spring通常所做的)。
更新
我想要注意:
- 我不希望HTTP客户端知道存在两种类型的汽车,
BlueBookCar
和AutoTraderCar
。 - 除了
id
之外,两种汽车类型的所有属性都不同。以后可能会有其他属性重叠。 - 出于维护原因和类之间的关系,我不想创建一个包含两个类属性集的第三个类。
ASP.NET MVC支持属性绑定排除。请参阅https://stackoverflow.com/a/8332917/1706691。Spring是否支持这个?
英文:
I have a Spring controller method that has two object params:
@GetMapping
public List<Car> getCars(BlueBookCar blueBookCar, AutoTraderCar autoTraderCar)
Both BlueBookCar
and AutoTraderCar
have a field named id
. I want the query param name id
in an HTTP GET request to be bound only to the BlueBookCar
instance.
For example, the following:
http://localhost/cars?id=123
Should result in blueBookCar
having an id
equal to 123. The autoTraderCar
id should be null. Instead, Spring sets both objects with an id
of 123.
How can I tell Spring to exclude binding id
for the autoTraderCar
? Other autoTraderCar
fields that have names matching query param names should be set (as Spring normally does).
Update
I meant to note that:
- I do not want HTTP clients to be aware of the existence of two types of cars,
BlueBookCar
&AutoTraderCar
- All properties except
id
are different between the two types of car. It's possible that later other properties may overlap. - I do not want to create a third class with the set of properties from both classes for maintenance reasons and because the classes have relationships.
ASP.NET MVC supports property binding exclusions. See https://stackoverflow.com/a/8332917/1706691. Does Spring support this?
答案1
得分: 1
你可以使用@InitBinder
来访问WebDataBinder
,以自定义如何将HTTP请求中的数据绑定到控制器方法中的特定参数对象。
在你的情况下,添加以下内容应该解决你的问题:
@Controller
public class CarController {
@InitBinder("autoTraderCar")
public void initAutoTraderCarDataBinder(WebDataBinder binder) {
binder.setDisallowedFields("id");
}
@GetMapping
public List<Car> getCars(BlueBookCar blueBookCar, AutoTraderCar autoTraderCar) {
}
}
英文:
You can use @InitBinder
which allows you to access WebDataBinder
for customising how to bind the data from the http request to a particular parameter object in the controller method.
In your case , adding the following should solve your problem :
@Controller
public class CarController {
@InitBinder("autoTraderCar")
public void initAutoTraderCarDataBinder(WebDataBinder binder) {
binder.setDisallowedFields("id");
}
@GetMapping
public List<Car> getCars(BlueBookCar blueBookCar, AutoTraderCar autoTraderCar){
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论