springboot之AOP配置

来源:互联网 发布:芒果tv mac版下载 编辑:程序博客网 时间:2024/04/30 08:59

package com.didi.controller;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class SleepHelper {

@Before("sleep()")public void beforeSleep(){    System.out.println("睡前刷牙---------");}@Pointcut("execution(* com.didi.domain.*.*(..))")public void sleep(){};@After("sleep()")public void wakeUp(){    System.out.println("醒来洗漱--------------");}

}

package com.didi.domain;

import org.springframework.stereotype.Component;

@Component
public class Man {

public void study(){    System.out.println("我正在学C++");}

}

package com.didi;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringUtils implements ApplicationContextAware {

private static ApplicationContext applicationContext;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {    this.applicationContext = applicationContext;    System.out.println("容器保存成功-----------");}public static ApplicationContext getApplicationContext(){    return applicationContext;}

}

package com.didi.controller;

import com.didi.SpringUtils;
import com.didi.domain.Man;
import org.hibernate.service.spi.InjectService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class AopController {

@RequestMapping("aopMapping")public void aop(){    Man man = (Man)SpringUtils.getApplicationContext().getBean("man");    man.study();}

}
访问:http://localhost:9006/aopMapping
控制台打印:
睡前刷牙———
我正在学C++
醒来洗漱————–

原创粉丝点击