creating custom annotation in spring mvc and getti

2020-06-22 05:31发布

问题:

I want to create custom annotation and put that annotation on method level using HttpServletRequest object. so far I did this:

Created annotation

@Target(value={ElementType.METHOD,ElementType.PARAMETER})
@Retention(value=RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Mapping
public @interface CheckSession{
    boolean isAuthenticate() default false;
}

created handler class

@Component
public class CheckSessionClass implements HandlerMethodReturnValueHandler,HandlerMethodArgumentResolver {




    @Override
    public Object resolveArgument(MethodParameter arg0,
            ModelAndViewContainer arg1, NativeWebRequest arg2,
            WebDataBinderFactory arg3) throws Exception {
        logger.info("......MY ANNOTATION CALLEDD.....resolveArgument");
        return null;
    }


    @Override
    public boolean supportsParameter(MethodParameter arg0) {
        logger.info("......MY ANNOTATION CALLEDD.....supportsParameter");
        return false;
    }


    @Override
    public void handleReturnValue(Object retutnValue, MethodParameter returnType,
            ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        CheckSession annotation;
        annotation=returnType.getMethodAnnotation(CheckSession.class);
        if(annotation.isAuthenticate()){
logger.info("......got request is aurhenticated..true");
        }else{
            logger.info("......got request is aurhenticated..false");
        }
    }


    @Override
    public boolean supportsReturnType(MethodParameter arg0) {
        logger.info("......MY ANNOTAION CALLEDD.....supportsReturnType");
        return false;
    }

}

created a controller to invoke annotation like this.

@Controller
public class MyController 
{
@RequestMapping(method={RequestMethod.GET, RequestMethod.POST})
@CheckSession(isAuthenticate=true)
    public ResponseEntity<String> mymethod (HttpServletRequest request)
    {
            ///my code here....
        }
}

My applicationContext.xml file is configured as auto component scan , but still my annotations class is not getting called.can anyone let me know my mistake.

回答1:

You still have to configure the interceptor in your application context (in spite of the auto-scan):

<bean id="checkSession" class="CheckSessionClass"/>

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
    <property name="defaultHandler">
        <ref bean="checkSession"/>
    </property>
</bean>