gpt4 book ai didi

java - 作为查询参数持有者的不可变类 - Spring MVC

转载 作者:太空宇宙 更新时间:2023-11-04 12:33:10 25 4
gpt4 key购买 nike

我想让我的查询参数类不可变(通过构造函数设置公共(public)最终字段)。有没有办法通过构造函数强制创建 SearchQueryParam 实例,并且不暴露可怕的 getter/setter?

这是有效的示例代码:

@RequestMapping(value = "/search", method = GET, produces = APPLICATION_JSON_VALUE)
public List<Result> search(SearchQueryParam searchQueryParam) {
//do stuff;
}


public class SearchQueryParam {
@DateTimeFormat(iso = DATE_TIME)
private DateTime from;
@DateTimeFormat(iso = DATE_TIME)
private DateTime to;

public DateTime getFrom() {
return from;
}

public void setFrom(DateTime from) {
this.from = from;
}

public DateTime getTo() {
return to;
}

public void setTo(DateTime to) {
this.to = to;
}
}

但我希望我的 SearchQueryParam 类看起来更像这样:

public final class SearchQueryParam {

@DateTimeFormat(iso = DATE_TIME)
public final DateTime from;
@DateTimeFormat(iso = DATE_TIME)
public final DateTime to;

public SearchQueryParam(DateTime from, DateTime to) {
this.from = from;
this.to = to;
}
}

最佳答案

您可以使用 WebArgumentResolver 来实现此目的。首先,您必须像这样编写自己的解析器

public class MySpecialArgumentResolver implements WebArgumentResolver {

public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) {
if (methodParameter.getParameterType().equals(MySpecialArg.class)) {
return new MySpecialArg("myValue");
}
return UNRESOLVED;
}
}

之后你需要在spring中注册这个解析器

<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean id="mySpecialArgumentResolver" class="..MySpecialArgumentResolver ">
</bean>
</mvc:argument-resolvers>

您可以阅读Use immutable objects in your Spring MVC controller by implementing your own WebArgumentResolver更多细节。在这篇文章中使用了旧的风格,在 spring 3.1 之后他们添加了 HandlerMethodArgumentResolver 并且你可以使用它。这里是新版本的示例 stackoverflow post

关于java - 作为查询参数持有者的不可变类 - Spring MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37613481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com