Skip to content

Instantly share code, notes, and snippets.

@kjunine
Last active June 4, 2016 11:44
Show Gist options
  • Select an option

  • Save kjunine/4975497 to your computer and use it in GitHub Desktop.

Select an option

Save kjunine/4975497 to your computer and use it in GitHub Desktop.
Spring MVC에서 WebArgumentResolver를 이용하여 @RequestAttribute 어노테이션 추가하기
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestAttribute {
/**
* The name of the request attribute.
*/
String value();
}
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
public class RequestAttributeArgumentResolver implements
HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterAnnotation(RequestAttribute.class) != null;
}
@Override
public Object resolveArgument(MethodParameter parameter,
ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
WebDataBinderFactory binderFactory) throws Exception {
RequestAttribute attr = parameter
.getParameterAnnotation(RequestAttribute.class);
return webRequest.getAttribute(attr.value(), WebRequest.SCOPE_REQUEST);
}
}
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addArgumentResolvers(
List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new RequestAttributeArgumentResolver());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment