ASPECTJ annotations and XML configuration implementations of Spring AOP (maven build)

Source: Internet
Author: User
Tags aop config manual execution getmessage throw exception throwable
XML Configuration 1. Interfaces and implementation classes
Public interface Usermanager {public
    String finduserbyid (int userId);
}
@Service public
class Usermanagerimpl implements Usermanager {
    @Override public
    String Finduserbyid (int UserId) {
        System.out.println ("---------Usermanagerimpl.finduserbyid ()--------");
        if (userId <= 0) {
            throw new IllegalArgumentException ("The user does not exist!")
        ;
        Return "Zhang San";
    }
}
2. Write a advice notification class separately for testing
public class Xmladvice {/** * Performs a call that does not block the core business before the core business is executed */private void Dobefore (Joinpoint joinpoint) {
        SYSTEM.OUT.PRINTLN ("---dobefore (). invoke--");
        System.out.println ("Do some security judgments and so on before executing the core business logic");
        System.out.println ("Can get what you need through Joinpoint");
    SYSTEM.OUT.PRINTLN ("-----End of Dobefore ()------"); /** * Manual control calls the core business logic, as well as the pre-and post-call processing * <p> * NOTE: When the core business throws an exception immediately after exiting the steering Afteradvice * executed Afteradvice Then turn to throwing Advice */private Object Doaround (Proceedingjoinpoint pjp) throws Throwable {System.out.prin
        TLN ("-----doaround (). Invoke-----");

        System.out.println ("Things like before advice can be done here");

        Call Core Logic Object RetVal = Pjp.proceed ();
        System.out.println ("Things like after advice" can be done here);
        SYSTEM.OUT.PRINTLN ("-----End of Doaround ()------");
    return retVal;
  /** * After the core business logic exits (including normal execution end and exception exit), execute this advice */private void Doafter (Joinpoint joinpoint) {      SYSTEM.OUT.PRINTLN ("-----doafter (). Invoke-----");
        System.out.println ("Do some logging operations and so on after executing the core business logic");
        System.out.println ("Can get what you need through Joinpoint");
    SYSTEM.OUT.PRINTLN ("-----End of Doafter ()------");
        /** * Core business logic call after normal exit, regardless of whether there is a return value, after normal exit, do this advice */private void Doreturn (Joinpoint joinpoint) {
        SYSTEM.OUT.PRINTLN ("-----doreturn (). Invoke-----");
        System.out.println ("The return value can be further processed here");
        System.out.println ("Can get what you need through Joinpoint");
    SYSTEM.OUT.PRINTLN ("-----End of Doreturn ()------");
        /** * Core business logic Call exception exited, execute this advice, handle error message */private void dothrowing (Joinpoint joinpoint, Throwable ex) {
        SYSTEM.OUT.PRINTLN ("-----dothrowing (). Invoke-----");
        SYSTEM.OUT.PRINTLN ("error message:" + ex.getmessage ());
        System.out.println ("Here is intended to perform core business logic errors, catch exceptions, and can do some logging operations, etc.");
        System.out.println ("Can get what you need through Joinpoint");
    SYSTEM.OUT.PRINTLN ("-----End of dothrowing ()------"); }
} 
3. Configure in the spring configuration file
<bean id= "Xmlhandler" class= "AOP. Xmladvice "/>
<aop:config>
        <aop:aspect id=" aspect "ref=" Xmlhandler ">
            <aop:pointcut Id= "pointusermgr" expression= "Execution (* intergrate.service.*.find* (..))" />

            <aop:before method= "Dobefore" pointcut-ref= "Pointusermgr"/>
            <aop:around method= "DoAround" pointcut-ref= "Pointusermgr"/>
            <aop:after method= "Doafter" pointcut-ref= "Pointusermgr"/>
            <aop : after-returning method= "Doreturn" pointcut-ref= "Pointusermgr"/> <aop:after-throwing method=
            "doThrowing "Throwing=" ex "pointcut-ref=" Pointusermgr "/>
        </aop:aspect>
    </aop:config>
4. Testing
@RunWith (Springjunit4classrunner.class)
@ContextConfiguration ("Classpath:spring-service.xml")
public Class Usermanagerimpltest {

    @Resource
    private Usermanager Usermanager;

    @Test public
    void Test () throws Exception {
        //normal run
        String user = Usermanager.finduserbyid (1);
        System.out.println ("User:" + user);

        System.out.println ("===== Gorgeous split line =======");

        Throw exception
        try {
            Usermanager.finduserbyid (0);
        } catch (Exception e) {
        }
    }
}

Output results

---dobefore (). invoke--here to do the core business logic, make some security judgments and so on can be joinpoint to obtain the required content-----End of the Dobefore ()----------- Doaround (). Invoke-----Here can do something similar to before advice---------Usermanagerimpl.finduserbyid ()--------here can do similar to after Advice thing-----End of doaround ()-----------doafter (). Invoke-----Here to execute the core business logic, do some logging operations and so on can be joinpoint to obtain the required content-- ---End of doafter ()-----------doreturn (). Invoke-----Where the return value can be further processed by Joinpoint to get what is needed-----End of doreturn ()----- -User: Zhang San ===== gorgeous split line =======---dobefore (). invoke--This is intended to perform some security decisions before implementing the core business logic, and so on joinpoint to get what you need-----End of Dobefore ()-----------doaround (). Invoke-----can do things like before advice here---------Usermanagerimpl.finduserbyid ()----- --------doafter (). Invoke-----This is intended to perform the core business logic, do some logging operations, and so on, can be joinpoint to get what you need-----End of doafter ()-----------
 Dothrowing (). Invoke-----Error message: The user does not exist! This is intended to perform core business logic errors, catch exceptions, do some logging operations, and so on, to get what you need through joinpoint-----End of dothrowing ()------

It is noteworthy that the order of execution of around and before and after. The order in which the 3 is executed depends on the order of configuration in the XML

If the configuration order is Aop:after-Aop:around->aop:before, then before and after will be included in the around. This is due to the particularity of the around, which can do operations similar to before and after. When the security judgment does not pass, it is possible to block the invocation of the core business logic, which is before. ASPECTJ Annotations interfaces and implementation classes

The same custom Aspcejadvice as above

@Aspect public class Aspcejadvice {/** * Pointcut * definition pointcut,pointcut name is Aspectjmethod (), this method has no return value and parameter
    * This method is an identity that does not make a call */@Pointcut ("Execution (* find* (..))") private void Aspectjmethod () {}/** * before * is executed before the core business execution and cannot block calls to the core business */@Before ("Aspectjmeth
        OD () ") public void Beforeadvice (Joinpoint joinpoint) {System.out.println ("-----beforeadvice (). Invoke-----");
        System.out.println ("Do some security judgments and so on before executing the core business logic");
        System.out.println ("Can get what you need through Joinpoint");
    SYSTEM.OUT.PRINTLN ("-----End of Beforeadvice ()------"); }/** * After core business logic exits (including normal execution end and exception exit), perform this advice */@After ("Aspectjmethod ()") public void AF
        Termethod (Joinpoint joinpoint) {System.out.println ("-----afteradvice (). Invoke-----");
        System.out.println ("Do some logging operations and so on after executing the core business logic");
        System.out.println ("Can get what you need through Joinpoint"); SYSTEM.OUT.PRINTLN ("-----End of Afteradvice ()------"); }/** * Around * Manual control calls the core business logic, as well as pre-and post-call processing, * <p> * Note: When the core business throws an exception, exit immediately and turn to Afteradvice * After executing Afteradvice, go to Throwingadvice */@Around (value = "Aspectjmethod ()") Public Object Aroundadvice (proceedingj
        Oinpoint pjp) throws Throwable {System.out.println ("-----aroundadvice (). Invoke-----");
        System.out.println ("Things like before advice can be done here");
        Call Core Logic Object RetVal = Pjp.proceed ();
        System.out.println ("Things like after advice" can be done here);
        SYSTEM.OUT.PRINTLN ("-----End of Aroundadvice ()------");
    return retVal; }/** * afterreturning * core business logic call after normal exit, regardless of whether there is a return value, after the normal exit, execute this advice */@AfterReturning (value = "Aspec Tjmethod () ", returning =" RetVal ") public void Afterreturningadvice (Joinpoint joinpoint, String retVal) {Syst
        EM.OUT.PRINTLN ("-----afterreturningadvice (). Invoke-----");
        System.out.println ("Return Value:" + retVal); System.out.println ("The return value can be further processed here");
        System.out.println ("Can get what you need through Joinpoint");
    SYSTEM.OUT.PRINTLN ("-----End of Afterreturningadvice ()------"); }/** * Core business logic call after exception exit, execute this advice, handle error message * <p> * Note: execution order after around advice */@AfterThrowin
        G (value = "Aspectjmethod ()", throwing = "ex") public void Afterthrowingadvice (Joinpoint joinpoint, Exception ex) {
        SYSTEM.OUT.PRINTLN ("-----afterthrowingadvice (). Invoke-----");
        SYSTEM.OUT.PRINTLN ("error message:" + ex.getmessage ());
        System.out.println ("Here is intended to perform core business logic errors, catch exceptions, and can do some logging operations, etc.");
        System.out.println ("Can get what you need through Joinpoint");
    SYSTEM.OUT.PRINTLN ("-----End of Afterthrowingadvice ()------");
 }
}
configuration in spring configuration file
<bean id= "Aspcejhandler" class= "AOP. Aspcejadvice "/>

<aop:aspectj-autoproxy/>
Test

Ditto

Output results

-----Aroundadvice (). Invoke-----Here you can do things like before advice-----beforeadvice (). Invoke-----This is meant to make some security decisions before executing the core business logic.
 You can get what you need through joinpoint-----End of Beforeadvice ()---------------Usermanagerimpl.finduserbyid ()--------
 Things like after advice can be done here-----End of Aroundadvice ()-----------afteradvice (). Invoke-----This is meant to do some logging operations after the core business logic is executed, and so on
 You can get what you need through joinpoint-----End of Afteradvice ()-----------afterreturningadvice (). Invoke-----Return Value: Zhang San The return value can be further processed here by Joinpoint to get what you need-----End of afterreturningadvice ()------User: Zhang San ===== gorgeous split line =======-----
 Aroundadvice (). Invoke-----Here you can do something similar to before advice-----beforeadvice (). Invoke-----Here to do some security judgment before executing the core business logic, etc. You can get what you need through joinpoint-----End of Beforeadvice ()---------------Usermanagerimpl.finduserbyid ()------------- Afteradvice (). Invoke-----Here is intended to execute the core business logic, do some logging operations and so on can be joinpoint to obtain the required content-----End of afteradvice ()-----------
 Afterthrowingadvice (). Invoke-----Error message: The user does not exist! This is intended to perform core business logic errors, to catch exceptions, to do some logging operations, and so on, to get the required JoinpointWhat to-----End of afterthrowingadvice ()------
 

The discovery of Aroundadvice, Beforeadvice, Afteradvice, and returningadvice through tests is based on the order of the annotations Advantages and disadvantages of XML configuration and annotation configuration XML configuration Benefits XML as the biggest advantage of Extensible Markup language is the ability for developers to tailor the applicable markup for the software to make the code more understandable. The use of XML configuration can make the software more extensible. Spring, for example, configures dependencies between classes in XML to maximize the scalability of the application. Proven validation mechanism to ensure program correctness. Using a Schema or DTD, you can validate the correctness of the XML and avoid an illegal configuration that results in an application error. The
modifies the configuration without changing the existing program. XML Configuration Disadvantage requires support for parsing tools or class libraries. Parsing XML is bound to affect application performance and consume system resources. Too many profiles cause management to become difficult. The compilation period cannot validate the correctness of its configuration items, or the error can only be run during runtime. The IDE cannot verify the correctness of the configuration items. It becomes difficult to find fault. Often the configuration of a hand mistakenly leads to inexplicable errors. Developers have to maintain code and configuration files at the same time, and development inefficiencies become inefficient. There are unspoken rules between the configuration item and the code. Change either party may affect the other party. Annotation Configuration Benefits are saved in the class file, reducing maintenance costs. No tooling support, no parsing required. Compile time to verify correctness, error checking becomes easy. Improve development efficiency. Note Configuration Disadvantage to modify a configuration item, you have to modify the Java file to recompile the packaged app. The configuration item is encoded in a Java file, which is poor extensibility.

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.