AOP面向切面編程的一個簡單案例


這是一個很簡單的案例,方便初學者更好理解切面的概念和實現;

我的目錄是這樣的,僅供參考:

1、先創建一個接口,接口中有兩個方法;

public interface StudentService {
    int insert();
    int delete();
}

2、寫一個實現類去實現接口中的方法;

@Service
public class StudentServiceImpl  implements StudentService {
    @Override
    public int insert() {
        System.out.println("插入一條學生記錄");
        //System.out.println("記錄日志");//將操作記錄保存數據庫中
        return 0;
    }

    @Override
    public int delete() {
        System.out.println("刪除一條學生記錄");
        //System.out.println("記錄日志");//將操作記錄保存數據庫中
        return 0;
    }
}

3、寫一個切面文件;

//日志切面
@Component
public class LogAspect {

    //通知
    public void log(){
        System.out.println("切面統一記錄日志!");
    }
}

4、寫一個配置文件,配置相關需要的數據;

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--開啟注解,配置掃描包,spring會在對應的包下去掃描配置了注解的類-->
    <context:component-scan base-package="before,spring,aop"></context:component-scan>

<!--    aop切面配置-->
    <aop:config>
<!--        配置切入點   id:切入點唯一標識; execution(表達式)  第一個*:訪問修飾符,表示任意的; *:匹配任意字符;  (..):任意的參數
            execution(表達式[訪問修飾符 包.類.方法(參數)])
-->
        <aop:pointcut id="logPointcut" expression="execution(* aop.StudentServiceImpl.*(..))"/>
<!--        配置通知  ref:關聯到切面-->
        <aop:aspect id="log" ref="logAspect">
<!--           before:前置通知; after:后置通知;  method:關聯到切面中的方法; pointcut-ref:關聯到切入點 -->
            <aop:before method="log" pointcut-ref="logPointcut"></aop:before>
        </aop:aspect>
    </aop:config>
</beans>

5、寫一個測試類,檢查是否成功;

@Controller
public class StudentAction {
    @Autowired
    private StudentService studentService;

    public void insert(){
        studentService.insert();
    }
    public void delete(){
        studentService.delete();
    }

    public static void main(String[] args) {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("/applicationContext2.xml");
        StudentAction studentAction = (StudentAction) applicationContext.getBean("studentAction");
        studentAction.delete();
        studentAction.insert();
    }
}

測試結果為:

看到這個結果說明我們就測試成功了;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM