Пользовательская аннотация | Не работает на сеттеров - PullRequest
0 голосов
/ 25 марта 2020

У меня есть требование сделать поле класса модели зашифрованным. Подход, который я выбрал, заключается в создании пользовательской аннотации. Где бы у меня ни была аннотация, она говорит, что я зашифрую ее значение.

Цель - создать аннотацию поля / метода. Если это аннотация метода, то я буду комментировать Setter.

Я написал код, но он не работает. Пожалуйста, помогите.

Класс Pojo, где я хочу зашифровать зарплату.

package com.example.springaop.model;

import com.example.springaop.customannotation.CustomAnnotation;
import com.example.springaop.customannotation.Encryptvalue;

public class Employee {

    private String empId;
    private String name;
    private int salary;

    public String getName() {
        return name;
    }

    @CustomAnnotation
    public void setName(String name) {
        this.name = name;
    }

    public String getEmpId() {
        return empId;
    }

    public void setEmpId(String empId) {
        this.empId = empId;
    }

    public int getSalary() {
        return salary;
    }
    @Encryptvalue
    public void setSalary(int salary) {
        this.salary = salary;
    }


}


Пользовательская аннотация

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Encryptvalue {

}

Класс EmployeeController

package com.example.springaop.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.springaop.customannotation.LogExecutionTime;
import com.example.springaop.model.Employee;
import com.example.springaop.service.EmployeeService;


@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping(value = "/add/employee", method = RequestMethod.GET)
    @LogExecutionTime
    public Employee addEmployee(@RequestParam("name") String name, @RequestParam("empId") String empId) throws InterruptedException {
        return employeeService.createEmployee(name, empId,1000);
    }

    @RequestMapping(value = "/remove/employee", method = RequestMethod.GET)
    public String removeEmployee( @RequestParam("empId") String empId) {

        employeeService.deleteEmployee(empId);

        return "Employee removed";
    }

}

Класс EmployeeService

package com.example.springaop.service;


import org.springframework.stereotype.Service;

import com.example.springaop.customannotation.CustomAnnotation;
import com.example.springaop.model.Employee;


@Service
public class EmployeeService {

    @CustomAnnotation
    public Employee createEmployee(String name, String empId, int salary) {
        Employee emp = new Employee();
        emp.setName(name);
        emp.setEmpId(empId);
        emp.setSalary(salary);
        return emp;
    }

    public void deleteEmployee(String empId) {

    }
}

Класс EmployeeServiceAspect

package com.example.springaop.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class EmployeeServiceAspect {

    @Before(value = "execution(* com.example.springaop.service.EmployeeService.*(..)) and args(name,empId)")
    public void beforeAdvice(JoinPoint joinPoint, String name, String empId) {
        System.out.println("Before method:" + joinPoint.getSignature());

        System.out.println("Creating Employee with name - " + name + " and id - " + empId);
    }

    @After(value = "execution(* com.example.springaop.service.EmployeeService.*(..)) and args(name,empId)")
    public void afterAdvice(JoinPoint joinPoint, String name, String empId) {
        System.out.println("After method:" + joinPoint.getSignature());

        System.out.println("Successfully created Employee with name - " + name + " and id - " + empId);
    }

    @Around("@annotation(com.example.springaop.customannotation.LogExecutionTime)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object proceed = joinPoint.proceed();
        long executionTime = System.currentTimeMillis() - start;
        System.out.println(joinPoint.getSignature() + " executed in " + executionTime + "ms");
        return proceed;
    }


    @Around("@annotation(com.example.springaop.customannotation.CustomAnnotation)")
    public Object customAnnotation(ProceedingJoinPoint joinPoint) throws Throwable {
        Object proceed = joinPoint.proceed();
        System.out.println(joinPoint.getSignature() + "############## Executed customAnnotation #################");
        return proceed;
    }

    @Around("@annotation(com.example.springaop.customannotation.Encryptvalue)")
    public Object Encryptvalue(ProceedingJoinPoint joinPoint) throws Throwable {
        Object proceed = joinPoint.proceed();
        System.out.println(joinPoint.getSignature() + "############## Executed Encryptvalue Annotation #################");
        return proceed;
    }
}

1 Ответ

1 голос
/ 25 марта 2020

Почему Аспект не работает

  1. Employee Экземпляр не является компонентом Spring. Spring AOP может только посоветовать боб. Пожалуйста, прочитайте справочную документацию
  2. @Before и @After Неправильно выражены точечные выражения для перехвата вызовов метода.
  3. Encryptvalue определяется как @Target(ElementType.FIELD) и пример показывает использование как @Target(ElementType.METHOD). В идеале код не должен компилироваться.

Если класс Employee можно сделать управляемым bean-компонентом Spring (в данном случае bean-компонентом), оба совета на основе аннотаций @Around будут работать как положено , Аналогичным образом, изменение выражения Pointcut следующим образом должно перехватывать вызов метода EmployeeService.createEmployee(). Чтобы сообщить всем вызовам методов EmployeeService, удалите часть and args(name,empId) выражения Pointcut.

пример:

@After(value = "execution(* com.example.springaop.service.EmployeeService.*(..)) and args(name,empId,salary)")
public void afterAdvice(JoinPoint joinPoint, String name, String empId,int salary) {..}
...