spring中基於註解的各種通知

導包

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>

接口類

public interface IAccountService {
    void saveAccount();
    void updateAccount(int i);
    int deleteAccount();
}

接口實現類,接口實現類上標記Service註解這樣就作爲bean加載到容器中

@Service("accountService")
public class AccountServiceImpl implements IAccountService {
    public void saveAccount() {
        System.out.println("保存賬戶");
    }

    public void updateAccount(int i) {
        System.out.println("修改賬戶:"+i);
    }

    public int deleteAccount() {
        System.out.println("刪除賬戶");
        return 0;
    }
}

通知工具類

@Component("logger")  //因爲不屬於服務層使用Component註解可以加載到容器中
@Aspect  //標註當前類是一個切面類
public class Logger {
    //配置切入點
    @Pointcut("execution(* *..*.*(int))")
    private void pt1(){}

    @Before("pt1()")
    public void beforePrintLog(){
        System.out.println("前置通知...");
    }
    @After("pt1()")
    public void afterPrintLog(){
        System.out.println("後置通知...");
    }
    @AfterReturning("pt1()")
    public void rturnPrintLog(){
        System.out.println("返回通知...");
    }
    @AfterThrowing("pt1()")
    public void exceptionPrintLog(){
        System.out.println("異常通知...");
    }

    @Around("pt1()")
    public Object arountPrintLog(ProceedingJoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        try {
            System.out.println("環繞通知中的前置通知...");
            Object proceed = joinPoint.proceed(args);
            System.out.println("環繞通知中的後置通知...");
            return proceed;
        } catch (Throwable throwable) {
            System.out.println("環繞通知中的異常通知...");
            throw  new RuntimeException(throwable);
        }
        finally {
            System.out.println("環繞通知中的最終通知...");
        }
    }
}

配置類

@Configuration  //標註這是一個配置類
@ComponentScan(basePackages = "com.itheima")  //標註掃描包範圍
@EnableAspectJAutoProxy   //標註可以使用AOP通知
public class SpringConfig {
}

測試類,放到單元測試中測試時需要導包

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.1.9.RELEASE</version>
</dependency>

並添加相關的註解RunWith和ContextConfiguration

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(classes = SpringConfig.class)  //標記要使用的配置類
public class AccountTest {

    @Autowired
    IAccountService accountService;
    @Test
    public void test(){
        accountService.updateAccount(1);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章