我有一个弹簧启动控制器,我的参数之一是枚举。枚举有一个字符串值。我想将枚举和控制器的值作为参数传递给我枚举。能做到吗?

 @RequestMapping(value = "/")
public MyResponse getResponse ( @RequestParam(value = "version") final ProjectVersion version ) {
   ...bla bla bla...
}

public enum ProjectVersion {
    VERSION_1 ("1.00")
    VERSION_2 ("2.00")

    private final String version;

    ProjectVersion ( String version ) {
        this.version = version;
    }

     @Override
     public String toString() {
        return this.version;
     }

}


我希望能够发出如下请求:

http://myhost.com/mypath?version=1.00

并进入控制器ProjectVersion.VERSION_1

有任何想法吗?

最佳答案

这是不可能的。您必须创建自定义转换器才能从String转换为ProjectVersion

例如,首先定义从StringProjectVersion的转换器:

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,则可以跳过注册。 (此代码未经测试)。

09-26 12:20