First Glimpse of AspectJ

Source: Internet
Author: User

AspectJ can be said to be a well-deserved black magic in Java. It is black magic, on the one hand because it is very powerful, can solve some traditional programming methodology cannot solve the problem, on the other hand, it is also quite obscure, with a relatively steep learning curve.

This article will take you to explore the next aspectj is what, what can do, and how to do, hope that through this article can let everyone first glimpse the doorway of ASPECTJ

What is AOP?

I believe many people first heard that AOP is learning spring, the author also. This concept really bothered me for a long time, in the end is AOP? AOP is the abbreviation for Aspect oriented programming, which, like OOP (Object oriented programming), represents a programming idea. The difference is that OOP is an abstraction of everything in the world, while AOP is an abstraction of the business process, and to some extent, AOP is a continuation of the idea of OOP and further encapsulation of the program.

So what can AOP do to solve the problem? As an example of adding a security policy to an existing system, we need to add code in different places in the code of each module to check the security policy. This approach is complex, error-prone, and cannot be reused. The security issue described here is a crosscutting concern, and developers need to find all the code that needs attention, inserting new business code in the middle of the existing code (as if slicing existing code). There are a number of issues like the security policy here, such as tracing.

ASPECTJ Basic Concepts

ASPECTJ is the Java implementation version of AOP, which defines the syntax of AOP, which can be said to be an extension to Java. The concept of Join point is introduced in relation to JAVA,ASPECTJ, with the introduction of three new structures, Pointcut (pointcuts), advice (notification), Inter-type Declaration (cross-type declarations), and aspect. Among them, pointcut and advice is the dynamic portion of the ASPECTJ, which is used to specify the conditions under which the execution is cut off and what action is taken to achieve the slice operation. As the name implies, the pointcut here is used to define what the situation is to be crosscutting, and advice refers to what we need to do in the crosscutting situation, so that pointcut and advice will dynamically affect the program's running flow. In a way, pointcut is similar to the breakpoint we hit when we use the IDE to debug the program, when the program executes to the point where we hit the breakpoint (running to the statement that satisfies our definition of pointcut, which is the join points connection), We can execute a script (execute the behavior defined in advice).

The Inter-type Declaration (cross-type declaration) in ASPECTJ is a static part of the ASPECTJ, which affects the static structure of the program, such as member variables, relationships between classes, and so on. Aspect is the encapsulation of the first three structures, similar to the classes in Java.

First ASPECTJ Program

Here we are not going to specifically discuss AspectJ's grammatical problems, but focus on how to write a simple demo with AspectJ. The development environment I use here is IntelliJ, and the project is built using MAVEN.

Maven Dependency

To run the ASPECTJ program, you first introduce the dependencies of the ASPECTJ Runtime:

<!--aspectj runtime classes --><dependency>    <groupId>org.aspectj</groupId>    <artifactId>aspectjrt</artifactId>    <version>1.8.9</version></dependency>

In addition to run-time dependencies, you also need aspectjweaver.jar :

<!--to introduce aspect to java class in load time--><dependency>    <groupId>org.aspectj</groupId>    <artifactId>aspectjweaver</artifactId>    <version>1.8.9</version></dependency>
A simple class

Write a simple class first:

package cc.databus.aspect;public class Account {    double balance = 200;    public boolean withdraw(int amount) {        if (balance < amount) {            return false;        }        balance = balance - amount;        return true;    }    @Override    public String toString() {        return "Account{" +                "balance=" + balance +                ‘}‘;    }}

The class defines an account class and provides a way to withdraw (withdraw).

Aspect definition

Create a AccountAspect.aj file to record the information before and after the withdrawal:

// aspect package cc.databus.aspect;public aspect AccountAspect {    // define a pointcut to pick up invoking Accont.withdraw     pointcut callWithDraw(int amount, Account account):            call(boolean Account.withdraw(int))             && args(amount)             && target(account);    // advice definition executing before enterring method body    before(int amount, Account acc): callWithDraw(amount, acc) {        System.out.println("Start withdraw " + amount + " from " + acc);    }    after(int amount, Account acc) returning (Object ret): callWithDraw(amount, acc) {        System.out.print("Finish withdraw, return "         + ret +", account after withdraw is: " +  acc);    }}

The Aspect file can be easily created by IntelliJ, and right-click on the package->new->aspect:

As you can see, the above Accountaspect.aj defines ASPECTJ's pointcut,advice and aspect.

Aspect Weaving (weaving)

Weaving .... Very strange word ... This refers to the process of implanting the advice defined in aspect into the runtime. Here we use a Maven plugin to aspect, this plugin is Mojo AspectJ Maven Plugin:

<plugins> <plugin> <groupId>org.codehaus.mojo</groupId> &LT;ARTIFACTID&GT;ASPECTJ -maven-plugin</artifactid> <version>1.7</version> <configuration> <com Pliancelevel>1.8</compliancelevel> <source>1.8</source> <target>1.8</t            Arget> <showWeaveInfo>true</showWeaveInfo> <verbose>true</verbose> <encoding>utf-8</encoding> </configuration> <executions> <executi                    On> <goals> <!--Use the goal to weave all your main classes-->                    <goal>compile</goal> <!--Use the goal to weave all your test classes-->        <goal>test-compile</goal> </goals> </execution> </executions> &Lt;/plugin></plugins> 

OK, let's write a UT to test if the aspect is in effect:

import cc.databus.aspect.Account;import org.junit.Before;import org.junit.Test;import static org.junit.Assert.assertFalse;import static org.junit.Assert.assertTrue;public class TestAccount {    private Account account;    @Before    public void before() {        account = new Account();    }    @Test    public void given20AndMin10_whenWithdraw5_thenSuccess() {        assertTrue(account.withdraw(5));    }        @Test    public void given20AndMin10_whenWithdraw100_thenFail() {        assertFalse(account.withdraw(100));    }}

Run the test, if the command line is like the output below, it means that aspect successfully weaves into our code, and pointcut successfully cut into the Account.withdraw call:

Start withdraw 5 from Account{balance=200.0}Finish withdraw, return true, account after withdraw is: Account{balance=195.0}Process finished with exit code 0
Summarize

In general, ASPECTJ is a rather obscure technology, but it has to be acknowledged as powerful. Based on the theory, this paper introduces the basic concepts of AOP and ASPECTJ, then introduces how to use ASPECTJ in the project with a simple demo program.

Article sync posted on my personal blog https://jianyuan.me, welcome to shoot bricks.
Portal: The first glimpse of AspectJ

First Glimpse of AspectJ

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.