如何在spring restful web service @controller中使用aop概念?

时间:2016-11-22 04:57:13

标签: spring rest aop

我是Spring Aop概念的新手。我想使用spring aop构建日志记录功能。我得到了很多例子,但我需要的是:

我有@controller类,每个方法都有requestmapping url,我希望每当该url命中aop建议时都应该调用。我已经尝试了很多。 你能纠正我吗?提前谢谢。

这是我的控制器类

 @Controller
 @RequestMapping("/hotel")
 public class BookingController {

  //private static final Logger logger =LoggerFactory.getLogger(BookingController.class);
// private static final Logger logger =  Logger.getLogger(BookingController.class);
 private static final Logger LOG =  Logger.getLogger(BookingController.class.getName());

/**
 * Simply selects the home view to render by returning its name.
 *
 * @param locale
 * @param model
 * @return
 */
@RequestMapping(method = RequestMethod.GET)
public String home(Locale locale, Model model) {
    System.out.println("hello");
    LOG.warning("Welcome home! The client locale is {}.");

    Date date = new Date();
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

    String formattedDate = dateFormat.format(date);

    model.addAttribute("serverTime", formattedDate);

    return "hotel";
}

@RequestMapping(value = "/book", method = RequestMethod.POST)
public String bookHotel(
        @RequestParam(value = "name", required = false) String name,
        @RequestParam(value = "city", required = false) String city,
        @RequestParam(value = "purpose", required = false) String purpose,
        @RequestParam(value = "idproof", required = false) String idproof,
        Model model, HttpServletRequest request) {

    //Save the required information in data base
    //......
    //......
    //Send the response back
    model.addAttribute("name", name);
    model.addAttribute("city", city);
    model.addAttribute("purpose", purpose);
    model.addAttribute("idproof", idproof);

    return "customerDetails";
}

@RequestMapping(value = "/book", method = RequestMethod.GET)
public String bookHotel(
        @RequestParam(value = "id", required = false) String id,
        Model model, HttpServletRequest request) {

    //get the required information in data base for customer Id
    //......
    //......
    //suppose we get these value from database
    String randomName = UUID.randomUUID().toString().substring(0, 4);
    String randomCity = UUID.randomUUID().toString().substring(0, 4);
    String randomPurpose = UUID.randomUUID().toString().substring(0, 4);
    String randomIdProof = UUID.randomUUID().toString().substring(0, 4);

    //Send the response back
    model.addAttribute("name", "Name " + randomName);
    model.addAttribute("city", "City " + randomCity);
    model.addAttribute("purpose", "Purpose " + randomPurpose);
    model.addAttribute("idproof", "IdProof " + randomIdProof);

    return "customerDetails";
}
 } 

这是我的ASPECT课程

@Aspect
@Component
public class LoggingHandler {

private static final Logger log = Logger.getLogger(BookingController.class.getName());

@Pointcut("within(@org.springframework.stereotype.Controller *)")
public void controller() {
}

@Pointcut("execution(* *.*(..))")
protected void allMethod() {
}

@Pointcut("execution(public * *(..))")
protected void loggingPublicOperation() {
}

@Pointcut("execution(* *.*(..))")
protected void loggingAllOperation() {
}

@Pointcut("within(org.learn.log..*)")
private void logAnyFunctionWithinResource() {
}

//before -> Any resource annotated with @Controller annotation 
//and all method and function taking HttpServletRequest as first parameter
@Before("controller() && allMethod() && args(..,request)")
public void logBefore(JoinPoint joinPoint, HttpServletRequest request) {

    System.out.println("--------------123------------");
    log.warning("Entering in Method :  " + joinPoint.getSignature().getName());
    log.warning("Class Name :  " + joinPoint.getSignature().getDeclaringTypeName());
    log.warning("Arguments :  " + Arrays.toString(joinPoint.getArgs()));
    log.warning("Target class : " + joinPoint.getTarget().getClass().getName());

    if (null != request) {
        log.warning("Start Header Section of request ");
        log.warning("Method Type : " + request.getMethod());
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            Object headerName = headerNames.nextElement();
            String headerValue = request.getHeader((String) headerName);
            log.warning("Header Name: " + headerName + " Header Value : " + headerValue);
        }
        log.warning("Request Path info :" + request.getServletPath());
        log.warning("End Header Section of request ");
    }
}

@Before("allMethod()")//applying pointcut on before advice  
public void myadvice(JoinPoint jp)//it is advice (before advice)  
{
    System.out.println("additional concern with before advice");
    System.out.println("Method Signature: " + jp.getSignature());
}

//After -> All method within resource annotated with @Controller annotation 
// and return a  value
@AfterReturning(pointcut = "controller() && allMethod()", returning = "result")
public void logAfter(JoinPoint joinPoint, Object result) {
    String returnValue = this.getValue(result);
    System.out.println("--------------123------------");
    log.warning("Method Return value : " + returnValue);
}
//After -> Any method within resource annotated with @Controller annotation 
// throws an exception ...Log it

@AfterThrowing(pointcut = "controller() && allMethod()", throwing = "exception")
public void logAfterThrowing(JoinPoint joinPoint, Throwable exception) {
    System.out.println("--------------123------------");
    log.warning("An exception has been thrown in " + joinPoint.getSignature().getName() + " ()");
    log.warning("Cause : " + exception.getCause());
}
//Around -> Any method within resource annotated with @Controller annotation 

@Around("controller() && allMethod()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {

    long start = System.currentTimeMillis();
    try {
        System.out.println("--------------123------------");
        log.warning("-------unnati----------");
        String className = joinPoint.getSignature().getDeclaringTypeName();
        String methodName = joinPoint.getSignature().getName();
        Object result = joinPoint.proceed();
        long elapsedTime = System.currentTimeMillis() - start;
        log.warning("Method " + className + "." + methodName + " ()" + " execution time : "
                + elapsedTime + " ms");

        return result;
    } catch (IllegalArgumentException e) {
        log.warning("Illegal argument " + Arrays.toString(joinPoint.getArgs()) + " in "
                + joinPoint.getSignature().getName() + "()");
        throw e;
    }
}

private String getValue(Object result) {
    String returnValue = null;
    if (null != result) {
        if (result.toString().endsWith("@" + Integer.toHexString(result.hashCode()))) {
            returnValue = ReflectionToStringBuilder.toString(result);
        } else {
            returnValue = result.toString();
        }
    }
    return returnValue;
}
}

以下是我的xml:

 <beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xsi:schemaLocation="
    http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context      http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/mvc     http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
            http://www.springframework.org/schema/aop     http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

<context:component-scan base-package="com.aopwithrestful.package1" />

<mvc:annotation-driven />

<aop:aspectj-autoproxy/>

<bean class="com.aopwithrestful.package1.LoggingHandler"/>

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>

我添加了以下库:

  • aspectjrt-1.6.11.jar
  • aspectjweaver-1.7.1.jar
  • CGLIB的节点p-3.2.4.jar
  • 弹簧AOP-4.3.2.RELEASE.jar

我仍然得到如下错误:

org.springframework.beans.factory.BeanCreationException:
Error creating bean with name
    'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping':
    Initialization of bean failed; nested exception is
        org.springframework.beans.ConversionNotSupportedException:
        Failed to convert property value of type
        [
            com.sun.proxy.$Proxy346 implementing org.springframework.web.accept.ContentNegotiationStrategy,
            org.springframework.web.accept.MediaTypeFileExtensionResolver,
            org.springframework.aop.SpringProxy,
            org.springframework.aop.framework.Advised,
            org.springframework.core.DecoratingProxy
        ] 
        to required type [org.springframework.web.accept.ContentNegotiationManager]
        for property 'contentNegotiationManager'; nested exception is
            java.lang.IllegalStateException:
            Cannot convert value of type 
            [
                com.sun.proxy.$Proxy346 implementing org.springframework.web.accept.ContentNegotiationStrategy,
                org.springframework.web.accept.MediaTypeFileExtensionResolver,
                org.springframework.aop.SpringProxy,
                org.springframework.aop.framework.Advised,
                org.springframework.core.DecoratingProxy
            ]
            to required type [org.springframework.web.accept.ContentNegotiationManager]
            for property 'contentNegotiationManager':
                no matching editors or conversion strategy found
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)

代码中的错误????

0 个答案:

没有答案