java用注解@annotation和切面@Aspect实现日志记录

1.日志切面定义

@Aspect
@Component
public class LogAspect {

    @Around(value = "@annotation(log)")
    public Object log(ProceedingJoinPoint joinPoint, Log log) throws Throwable {
        Object result = joinPoint.proceed();
        //do something else
        Map map = new HashMap<>();
        map.put("userDo",result);
        Object id = new SimpleTemplateEngine().createTemplate(log.id()).make(map);
        Object content = new SimpleTemplateEngine().createTemplate(log.content()).make(map);
        return result;
    }
}

2.日志注解定义

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Log {
    String id() default "";
    String content() default "";
}

3.实体类定义

@Data
public class UserDo {
    private Long id;
    private String userName;
    private int age;
}

4.接口和实现定义

public interface UserService {
    UserDo add(UserDo userDo);
}



@Component
public class UserServiceImpl implements UserService {
    @Override
    @Log(id = "${userDo.id}", content = "${userDo}")
    public UserDo add(UserDo userDo) {
        userDo.setId(1L);
        userDo.setUserName("张三");
        userDo.setAge(18);
        return userDo;
    }
}

 

你可能感兴趣的:(=======java,annotation,Aspect,Groovy)