我有一个弹簧启动控制器,我的一个参数是一个Enum。枚举有一个字符串值。我想将enum和控制器的值作为参数传递给我Enum。可以这样做吗?
CreateLife: function (browser) {
browser.getValue('#LifeID', function (r) {
a = r.value;
browser.execute(function () {
LifeTemplatesManager.loadAddOnlineItem(a); //doesn't work/The value of 'a' is not being passed.
});
console.log("ID of newly created Life", a);
}
}
我希望能够提出如下请求:
http://myhost.com/mypath?version=1.00
并在控制器中获取ProjectVersion.VERSION_1
有什么想法吗?
答案 0 :(得分:9)
这是不可能的。您必须创建自定义转换器才能从String
转换为ProjectVersion
。
例如,首先将转换器从String
定义为ProjectVersion
:
public class ProjectVersionConverter implements ConditionalGenericConverter {
@Override
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
return targetType.getType().equals(ProjectVersion.class);
}
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(String.class , ProjectVersion.class));
}
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
return ProjectVersion.findByVersion((String)source);
}
}
然后注册:
@Configuration
public class CustomWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new ProjectVersionConverter());
}
}
如果定义ProjectVersionConverter
有一个Spring bean,则可以跳过注册。 (此代码尚未经过测试)。
答案 1 :(得分:2)
因为您需要将参数传递给CREATE OR REPLACE VIEW v_team_result AS
SELECT my_column1 a,
j.key::integer b,
to_json(j.value->'c')::text::bigint c,
to_json(j.value->'d')::text::bigint d
FROM my_table, jsonb_each(my_json_column) j;
方法(对于每个请求),所以干净的解决方案是使用HandlerMethodArgumentResolver,这样
Spring容器可以动态地将ProjectVersion参数注入Controller方法,如下所示:
Controller
课程:
ProjectVersionArgumentResolver
Spring-boot ApplicationLauncher类:
public class ProjectVersionArgumentResolver implements
HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.getParameterType().equals(ProjectVersion.class);
}
@Override
public Object resolveArgument(MethodParameter methodParameter,
ModelAndViewContainer modelAndViewContainer,
NativeWebRequest nativeWebRequest,
WebDataBinderFactory webDataBinderFactory) throws Exception {
return ProjectVersion.fromString(nativeWebRequest.getParameter("version"));
}
}
public class MyProjectApplicationLauncher extends WebMvcConfigurerAdapter {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver>
argumentResolvers) {
//add the new resolver
argumentResolvers.add(new MyMethodArgumentResolver());
}
public static void main(String[] args) {
SpringApplication.run(MyProjectApplicationLauncher.class, args);
}
}
课程:
ProjectVersion