Java aop面向切面編程(aspectJweaver)案例詳解

面向切面編程的目的就是:在不改變別人的代碼的前提下,在別人代碼方法執行前或後,執行(切入自己的邏輯)
準備:idea+maven+aspectjweaver-1.8.9.jar
結構圖:

aop

pom.xml內容

 <dependencies>
        <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjrt</artifactId>
                <version>1.8.9</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjtools</artifactId>
            <version>1.8.9</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.9</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>aspectj-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <complianceLevel>1.8</complianceLevel>
                    <source>1.8</source>
                    <target>1.8</target>
                    <aspectDirectory>src/main/java</aspectDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>

切面類

  public aspect Staspect {

    public pointcut kkMethod(): execution(public String aop.Test.kk());
    before(): kkMethod() {
        System.out.println("先執行我");
    }
}

主類

public class Test {
    public String kk(){
        return "23";
    }
    public static void main(String[] args) {
        Test test=new Test();
        System.out.println(test.kk());

    }
}

新建一個aop.xml(在META-INFO文件夾下)

<?xml version="1.0" encoding="UTF-8" ?>
<aspectj>
    <aspects>
        <aspect name="aop.Staspect"/>
    </aspects>
    <weaver options="-XaddSerialVersionUID"></weaver>
</aspectj>

打jar包,執行命令:mvn clean package
註意我的結構圖,classes下面如果有兩個類就是編譯成功瞭
挑出jar包,執行命令:
java -javaagent:/home/admin/aspectjweaver-1.8.9.jar -classpath aspecttest-1.0-SNAPSHOT.jar aop.Test

註意:-javaagent後面的參數是你電腦aspectjweaver-1.8.9.jar的路徑

到此這篇關於Java aop面向切面編程(aspectJweaver)案例詳解的文章就介紹到這瞭,更多相關Java aop之aspectJweaver內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: