Spring notes-a simple example of using spring API to implement AOP, springapiaop

Source: Internet
Author: User

Spring notes-a simple example of using spring API to implement AOP, springapiaop

Another important idea of Spring is AOP, which provides a mechanism to execute additional code before and after running the business, the Filter in Servlet is an embodiment of the AOP idea. Let's take a look at it through an example below.

Suppose we need to add a set of logs when performing CRUD operations on the database, that is, add a sentence before and after the CRUD method is executed to implement simple Aspect-Oriented Programming. I use spring4, which may be different from the previous version in the configuration file.

To use spring API to implement AOP, in addition to the core jar package essential to spring, two jar packages need to be imported:

The header file of the configuration file also needs to be slightly modified. For details, see beans. xml.

UserService class (Omitted database operation code, only simple printing to simulate ):

Public class UserService {public void add () {System. out. println ("Add User");} public void delete () {System. out. println ("delete user");} public void update () {System. out. println ("Modify user");} public void search () {System. out. println ("query user ");}}

Log class (executed before the addition, deletion, modification, and query method is executed ):

Public class Log implements MethodBeforeAdvice {/*** method: The called method object * arg1: The parameter * target of the called method: target Object of the called Method */@ Override public void before (method Method, Object [] arg1, Object target) throws Throwable {System. out. println (target. getClass (). "+ method in getName () +. getName () + "method executed ");}}

AfterLog class (executed after adding, deleting, modifying, and querying methods ):

Public class AfterLog implements AfterReturningAdvice {/*** returnValue: Return Value Type * method: called method object * arg1: parameter of the called method * target: target Object of the called Method */@ Override public void afterReturning (Object returnValue, method Method, Object [] args, Object target) throws Throwable {System. out. println (target. getClass (). "+ method in getName () +. getName () + "The method is successfully executed, and the returned value is" + returnValue );}

Spring configuration file (beans. xml ):

<? 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: 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id = "UserService" class = "com. wang. service. userService "> </bean> <bean id =" log "class =" com. wang. log. log "> </bean> <bean id =" afterlog "class =" com. wang. log. afterLog "> </bean> <aop: config> <! -- "*" Indicates all methods as wildcards ".. "represents any number of parameters --> <aop: pointcut expression =" execution (* com. wang. service. userService. * () "id =" pointcut "/> <aop: advisor advice-ref =" log "pointcut-ref =" pointcut "/> <aop: advisor advice-ref = "afterlog" pointcut-ref = "pointcut"/> </aop: config> </beans>

Test code testDemo:

   @Test    public void test1(){        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");        UserService userService=(UserService)context.getBean("userService");        userService.add();        userService.search();    }

Run the test and you can see the printed result on the console:

The add method in com. wang. service. UserService is executed.
Add User
The add method in com. wang. service. UserService is successfully executed, and the return value is null.

The search method in com. wang. service. UserService is executed.
Query users
The search method in com. wang. service. UserService is successfully executed, and the return value is null.

In the configuration file, we see some such code:

<Aop: config> <! -- "*" Indicates all methods as wildcards ".. "represents any number of parameters --> <aop: pointcut expression =" execution (* com. wang. service. userService. * () "id =" pointcut "/> <aop: advisor advice-ref =" log "pointcut-ref =" pointcut "/> <aop: advisor advice-ref = "afterlog" pointcut-ref = "pointcut"/> </aop: config>

Let's introduce several AOP related concepts. This is a better understanding:

  • Aspect (Aspect): In this example. add (), delete (), and other methods all have some code. In a real program, it is not just a simple print statement but some meaningful Code. The Code can be seen as AOP.Section.
  • Notification (Advisor): In this example, two log classes can be called interceptors, both of which implement a * Advisor interface. These two classes refer toNotificationOnce Spring meets the conditions, it will send a notification. Unlike the notifications we mentioned in our daily life, notifications in Spring have code execution and can implement some function.
  • Pointcut: When configuring the Interceptor (<aop-config>), all methods configured in xml for UserService use the interceptor, this configuration is completed through a class that has been written in spring. This class can be used to configure the methods for which the interceptor is used and "" is entered from that place. wildcard characters can be used for configuration.

In short: "entry point" inserts code into "where" and "notification" inserts "What code ".

 

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.