Spring core concepts: AOP and spring core aop

Source: Internet
Author: User
Tags log log

Spring core concepts: AOP and spring core aop
I. Concept of AOP

AOP (Aspect Oriented Programming) is short for Aspect-Oriented Programming. It is mainly used to enhance code processing.

Understand the meaning of Aspect-Oriented Programming: Add new functions to the code without changing the original program.

To implement Aspect-Oriented Programming, you need to understand two concepts:

> Entry point: you can insert enhancement methods, such as the fun () method of the original object.

> Enhanced processing type: New features are inserted before the original object fun () method.

Ii. Simple Spring AOP Application

1. Create a java Project

2. Download the jar packages required by the Spring AOP and AspectJ frameworks from the official website, and add the jar files to the project.

3. Add the User entity class to the Project

package com.jbit.fsd.entity;public class User {private int id;private String username;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}}

4. Add data access layer interfaces and implementation classes, and add corresponding methods

Package com. jbit. fsd. dao; import java. util. list; import com. jbit. fsd. entity. user; // data access layer interface public interface UserDao {public List <User> getAll (); public void addUser (User user );}

Implementation class:

Package com. jbit. fsd. dao. impl; import java. util. arrayList; import java. util. list; import com. jbit. fsd. dao. userDao; import com. jbit. fsd. entity. user; public class UserDaoImpl implements UserDao {@ Overridepublic List <User> getAll () {// The operation database reads all data List <User> list = new ArrayList <User> (); list. add (new User (); list. add (new User (); list. add (new User (); return list;} @ Overridepublic void addUser (User user) {System. out. println ("successfully added ");}}

5. Add business processing layer interfaces and implementation classes

package com.jbit.fsd.service;import java.util.List;import com.jbit.fsd.dao.UserDao;import com.jbit.fsd.entity.User;public interface UserService {public List<User> getAll();public void addUser(User user);}

Implementation class:

Package com. jbit. fsd. service. impl; import java. util. list; import com. jbit. fsd. dao. userDao; import com. jbit. fsd. entity. user; import com. jbit. fsd. service. userService; public class UserServiceImpl implements UserService {private UserDao dao; // public void setDao (UserDao dao) {this. dao = dao ;}@ Overridepublic List <User> getAll () {System. out. println ("adding the user's business is being executed! "); Return dao. getAll () ;}@ Overridepublic void addUser (User user ){
System. out. println ("Adding User Service is being executed! "); Dao. addUser (user );}}

6. Add an AOP enhancement class

Package com. jbit. fsd. aop; import org. apache. commons. logging. log; import org. apache. commons. logging. logFactory; public class ServiceLoging {private Log log = LogFactory. getLog (this. getClass (); public void beforeService () {log.info ("the aop method is called! ");}}

7. Create the applicationContext. xml file in the src directory.

<? Xml version = "1.0" encoding = "UTF-8"?> <! -- Application context definition for JPetStore's business layer. -Contains bean references to the transaction manager and to the DAOs in-dataAccessContext-local/jta. xml (see web. xml's "contextConfigLocation "). --> <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" xmlns: tx = "http: // w Ww.springframework.org/schema/tx "xsi: schemaLocation =" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd "> <! -- Implement decoupling with interface-oriented programming --> <bean id = "userDao" class = "com. jbit. fsd. dao. impl. userDaoImpl "> </bean> <bean id =" userServiceImpl "class =" com. jbit. fsd. service. impl. userServiceImpl "> <property name =" dao "ref =" userDao "> </property> <! -- Property injection --> </bean> <! -- Configuration section --> <bean id = "serviceLogging" class = "com. jbit. fsd. aop. ServiceLoging"> </bean> <aop: config> <! -- Configure the entry point --> <aop: pointcut expression = "execution (public void addUser (com. jbit. fsd. entity. User)" id = "servicePointcut"/> <! -- Combine the aspect and entry point --> <aop: aspect ref = "serviceLogging"> <aop: before method = "beforeService" pointcut-ref = "servicePointcut"/> </aop: aspect> </aop: config> </beans>

8. Test the main method:

package com.jbit.fsd.test;import java.util.List;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.jbit.fsd.dao.UserDao;import com.jbit.fsd.entity.User;import com.jbit.fsd.printer.Printer;import com.jbit.fsd.service.UserService;import com.jbit.fsd.service.impl.UserServiceImpl;public class Test {/** * @param args */public static void main(String[] args) {ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");UserService dao=(UserService) ac.getBean("userServiceImpl");dao.addUser(new User());}}

Note:

1. Add the aop namespace to The. xml file and import the labels related to the aop configuration.

2. Configure aop in the <aop: config> label, and configure the entry point in the <aop: pointcut> label.

3.exe cution is the entry point identifier, and brackets are the entry point expressions. The configuration method needs to be enhanced.

4. There are several Fuzzy Matching methods for the entry point expression:

> Public * addUser (com. able. entity. User). "*" indicates the return values of all types.

> Public void * (com. able. entity. User), "*" indicates that all method names are matched.

> Public void addUser (...), "..." indicates the number and type of all parameters that match.

> * Com. able. service. *. * (..) indicates that all methods of all classes under the com. able. service package are matched.

> * Com. able. service... * (), which matches the com. able. service package and all methods of all classes in the sub-package.

Iii. Introduction to enhanced processing types

1. Pre-enhancement processing

Features: the enhancement processing is woven before the target method.

<Aop: before method = "beforeService" poontcut-ref = "servicePointcut"/>

To obtain the entry point information in this method, use the following method:

Package com. jbit. fsd. aop; import org. apache. commons. logging. log; import org. apache. commons. logging. logFactory; import org. aspectj. lang. joinPoint; public class ServiceLoging {private Log log = LogFactory. getLog (this. getClass (); public void beforeService (JoinPoint joinPoint) {System. out. println ("aop method called"); System. out. println ("connection point object:" + joinPoint. getTarget (). getClass (). getSimpleName (); System. out. println ("connection point method:" + joinPoint. getSignature (); System. out. println ("connection point method parameters:" + joinPoint. getArgs () [0]) ;}}

2. Post-enhancement processing

Feature: after the target method is executed normally (no exception occurs), the enhancement processing is woven.

<Aop: after-returning method = "afterReturning" pointcut-ref = "servicePointcut"/>

To obtain the return value, Add returning = "returnVal"

<Aop: after-returning method = "aft" pointcut-ref = "ser" returning = "returnVal"/>

public void afterService(Object returnVal){System.out.println(returnVal);}

3. Exception Enhancement

Feature: After an exception occurs in the target method, it is woven into the enhanced processing.

<Aop: after-throwing mehod = "" pointcut-ref = "" throwing = "ex"/>

Add throwing = "ex" if you need to get the exception object"

public void afterThrowing(Exception ex){System.out.println(ex.getMessage());}

4. Final Enhancement

Features: whether or not an exception is thrown in the method, It will be further organized at the end of the target method, similar to finally.

<Aop: after method = "after" pointcut-ref = "servicePointcut"/>

5. Enhanced surround Processing

Feature: the enhancement processing can be woven before and after the target method.

<Aop: around method = "" pointcut-ref = ""/>

Public Boolean around (ProceedingJoinPoint pjp) throws Throwable {System. out. println ("parameter of the target method:" + pjp. getArgs () [0]); Boolean B = null; if (true) {B = (Boolean) pjp. proceed (pjp. getArgs ();} return B ;}
4. Use AspectJ to simplify AOP Configuration

Spring has two methods for AOP Configuration:

> Implement simple AOP configuration in the schema form, that is, the usage of the above example.

> Use annotation to simplify the configuration of AOP.

AspectJ is a cross-section framework. AspectJ defines the AOP syntax.

To use @ AspectJ, you must use JDK or later.

Steps:

1. Write the business class (same as the method above ).

2. Write the partition class.

Package com. jbit. ssh. aop; import org. aspectj. lang. annotation. after; import org. aspectj. lang. annotation. aspect; import org. aspectj. lang. annotation. before; @ Aspect // 1. mark a public class AspectTest {@ Before ("execution (* com. jbit. ssh. service .. *. *(..)) ") // 2. define cut point and enhancement type (cut point expression) public void ba () {// 3. enhanced processing fun 4. configure xmlSystem. out. println ("pre-enhancement -------") ;}@ After ("execution (* com. jbit. ssh. service .. *. *(..)) ") public void aa () {System. out. println ("post enhancement ------");}/*** @ before indicates pre-enhancement * @ AfterReturning: Indicates post-enhancement processing * @ Around: Indicates surround enhancement processing * @ AfterThrowing: exception enhancement processing * @ After: Indicates final enhancement processing */}

3. Write a configuration file to implement AOP

<? Xml version = "1.0" encoding = "UTF-8"?> <! -- Application context definition for JPetStore's business layer. -Contains bean references to the transaction manager and to the DAOs in-dataAccessContext-local/jta. xml (see web. xml's "contextConfigLocation "). --> <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" xmlns: tx = "http: // w Ww.springframework.org/schema/tx "xmlns: p =" http://www.springframework.org/schema/p "xmlns: context =" http://www.springframework.org/schema/context "xsi: schemaLocation =" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsdhttp://www.spri Ngframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd "> <! -- 4. @ AspectJ-based drive --> <aop: aspectj-autoproxy/> <bean class = "com. jbit. ssh. aop. aspectTest "> </bean> </beans>

  

 

Related Article

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.