带有Spring Boot的AOP - 方面无效

时间:2017-09-10 06:54:48

标签: spring spring-boot aop spring-aop

我创建了一个自定义注释,但我无法使其工作。没有错误,但我没有输出。

您可以在此处找到完整代码: https://bitbucket.org/Deviad/springfood/src/f2d87086c47db724eca92e03e008612e30a17e1c/?at=acl_not_working

----- Acl.java -----

package com.davidepugliese.springfood.security;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})

public @interface Acl{
    String value();
}

----- AclAspect.java -----

package com.davidepugliese.springfood.security;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class AclAspect {
    @Pointcut(value = "@annotation(com.davidepugliese.springfood.security.Acl)" + "&& args(accLevel)")
    public void accessControl(Acl accLevel) {
    }

    @Around(value = "accessControl(accLevel)", argNames = "joinPoint,accLevel")
    public void value(ProceedingJoinPoint joinPoint, Acl accLevel) throws Throwable {
//        Object[] originalArguments = joinPoint.getArgs();
//
//        Object[] newArguments = new Object[1];
//        System.out.println(newArguments[0]);
//        newArguments[0] = ((String)originalArguments[0]).toUpperCase();

//        joinPoint.proceed(newArguments);

          System.out.println("Hello world!");
          joinPoint.proceed();

    }
}

----- UserController.java -----

package com.davidepugliese.springfood.controllers;

import com.davidepugliese.springfood.domain.UserDAO;
import com.davidepugliese.springfood.models.User;
import com.davidepugliese.springfood.security.Acl;
import com.davidepugliese.springfood.services.EncryptionUtilities;
import com.davidepugliese.springfood.adt.IEmail;
import com.sun.javaws.exceptions.InvalidArgumentException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/user/")
public class UserController {
    @Value("${jwt.secret}")
    private String secretKey;
    private UserDAO userService;
    @Autowired
    public UserController(UserDAO userService) {
        this.userService = userService;
    }




    @RequestMapping(value="/{id}", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
    @Acl("asdasdas")
    public @ResponseBody
    User getUser(@PathVariable Integer id) {
        return userService.getUser(id);
    }

    @RequestMapping(value="/username/{username:.+}", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
    public
    ResponseEntity getUserByUsername(@PathVariable String username) throws InvalidArgumentException {

            Object data = userService.getUserByUsername(IEmail.create(username));
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("data", data);
            return ResponseEntity.ok(response);
    }

    @RequestMapping(value="/add", method=RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
    @ResponseStatus( HttpStatus.CREATED )
    public
    ResponseEntity addUser(@RequestBody User data, Model model) {

        try {
            User user = new User();
            user.setUsername(data.getUsername());
            user.setPassword(EncryptionUtilities.encryptPassword(data.getPassword()));
            this.userService.saveUser(user);
            Map<String, String> response = new HashMap<>();
            response.put("status", "success");
            response.put("message", "User created successfully");
            return ResponseEntity.ok(response);
        } catch (DataIntegrityViolationException e) {
            Map<String, String> response = new HashMap<>();
            response.put("status", "fail");
            response.put("reason", "Username exists already");
            return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(response);
        }
    }
    @RequestMapping(value="/login", method=RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
    @ResponseStatus( HttpStatus.OK )
    public
    ResponseEntity login(@RequestBody User login, Model model) {


            String jwtToken;

            if (login.getUsername() == null || login.getPassword() == null) {
                Map<String, String> response = new HashMap<>();
                response.put("status", "fail");
                response.put("reason", "Insert username and password");
                return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(response);
            }

            String email = login.getUsername();

            String password = login.getPassword();

            User user = userService.getUserByUsername(email);

            if (user == null) {
                Map<String, String> response = new HashMap<>();
                response.put("status", "fail");
                response.put("reason", "Username not found");
                return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(response);
            }

            String pwd = user.getPassword();
            if (!EncryptionUtilities.matches(password, pwd)) {
                Map<String, String> response = new HashMap<>();
                response.put("status", "fail");
                response.put("reason", "Wrong password");
                return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(response);
            }
            jwtToken = Jwts.builder().setSubject(email).claim("roles", "user").setIssuedAt(new Date())
                    .signWith(SignatureAlgorithm.HS256, secretKey).compact();
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("data", jwtToken);
            return ResponseEntity.ok(response);
        }
}

2 个答案:

答案 0 :(得分:1)

用此替换AclAspect.java并尝试

package com.davidepugliese.springfood.security;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class AclAspect {
    @Pointcut(value = "@annotation(accLevel)")
    public void accessControl(Acl accLevel) {
    }

    @Around(value = "com.davidepugliese.springfood.security.accessControl(accLevel)")
    public void value(ProceedingJoinPoint joinPoint, Acl accLevel) throws Throwable {
//        Object[] originalArguments = joinPoint.getArgs();
//
//        Object[] newArguments = new Object[1];
//        System.out.println(newArguments[0]);
//        newArguments[0] = ((String)originalArguments[0]).toUpperCase();

//        joinPoint.proceed(newArguments);

          System.out.println("Hello world!");
          joinPoint.proceed();

    }
}

答案 1 :(得分:0)

因此,为了实现这一点,我必须考虑到@ m-deinum和@rakesh的答案。

你可以在我的回购中查看。 https://bitbucket.org/Deviad/springfood/src/c822a305edbd62d0b57df5b089f4d8e42682d22a/?at=master