Spring's aspect-oriented programming AOP (II)

Source: Internet
Author: User
Tags connection pooling

Brief introduction

When the accumulated knowledge points to a certain amount of time, learning new knowledge becomes much easier. Hope that the next study will go on smoothly. Today's knowledge is quite simple, mainly AOP-oriented programming. It involves the Jdkproxy and cglib two proxy classes, how to use good, to understand deeply. It's a lot easier to learn spring programming.

Proxy mode
1. Proxy mode introduction proxy mode in English is called proxy or surrogate, Chinese can be translated as "agent", the so-called agent, is one person or an institution acting on behalf of another person or another agency. In some cases, a client does not want or cannot refer directly to an object, whereas a proxy object can act as an intermediary between the client and the target object 2. The agent is divided into three roles abstract topic role: Is the proxy class and the proxy class common interface proxy topic role: Is the proxy class holds a reference to the proxy class, the proxy class is usually passed on the client call to the object now created before or after the operation of an action, Instead of simply passing the call to the existing object real topic: It is the real object that the proxy class produces 3. JDK Dynamic Agent public static <T> T Getbean (final class<t> clazz) {Iuserservice Proxyservice = (iuserservice) proxy.ne Wproxyinstance (Clazz.getclassloader (), Clazz.getinterfaces (), new Invocationhandler () {Object RetVal = null;@ Overridepublic object Invoke (Object proxy, Method method, object[] args) throws Throwable {if ("Saveuser". Equals ( Method.getname ()) | | "UpdateUser". Equals (Method.getname ())) {security (); retVal = Method.invoke (Clazz.newinstance (), args);//Call target object} return retVal;});} Summary: 1, because the proxy class generated by the Jdkproxy implements the interface, so all the methods in the target class are in the proxy class. 2. All methods of the generated proxy class intercept all methods of the target class. The content of the Invoke method in the interceptor is exactly the constituent of each method of the proxy class. 3, the use of Jdkproxy mode must have an interface exists. 4. The three parameters in the Invoke method can access the API of the calling method of the target class, the parameters of the called method, and the return type 4 of the called method. Cglib Agent Private Class clazz;public <T> T getenhancer(Class<t> clazz) {this.clazz = Clazz; Enhancer enhancer = new enhancer (); Enhancer.setclassloader (Clazz.getclassloader ()); Enhancer.setsuperclass (Clazz); Enhancer.setcallback (this); return (T) enhancer.create ();} @Overridepublic Object Intercept (object proxy, Method method, object[] Args,methodproxy Proxymethod) throws Throwable {Ob Ject RetVal = null;if ("Saveuser". Equals (Method.getname ()) | | "UpdateUser". Equals (Method.getname ())) {security (); retVal = Method.invoke (Clazz.newinstance (), args); System.out.println (Proxymethod.getsignature (). GetName () + ">>>>>>>>>");} return retVal;} Summary: Cglib agent 1. First to implement Methodinterceptor, rewrite intercept method 2. Create enhancer object, class loader, load class, callback method Setcallback, create object
Spring-oriented tangent programming
1. Spring aspect-oriented programming introduction Spring provides 2 proxy modes, one is the JDK proxy and the other Cglib proxy 1. If the target object implements several interfaces, spring uses the JDK's Java.lang.reflect.Proxy class proxy. 2. If the target object does not implement any interfaces, spring uses the Cglib library to generate a subclass of the target object. Note: When developing the programming of the interface as much as possible, (1) It is better to create a proxy for the interface than to create a proxy for the class, because a more loosely coupled system is produced. (2) The method marked as final cannot be notified. Spring is the generation of subclasses for the target class. Any method that needs to be notified is replicated and the notification is woven into. The final method is not allowed to be overridden. (3) Spring supports only method connection points, and connection point 2 for properties is not supported. AOP concept Jdkproxy proxy Springaop target object (target) Interceptor class plane (Aspect) method notification in interceptor Class (Advice) The collection Pointcut of methods in the target class that is intercepted (Pointcut) Method that is called by the client (target class target method) connection point (Joinpoint) proxy class AOP proxy (jdk&cglib) proxy class generation process weaving (Weaving) * * * Notifications are divided according to the location of the target method in the interception target class: Pre-notification, post-notification, final notification, surround notification, exception notification

AOP Programming Implementation Method
1. XML form implementation 1). SPRINGAOP programming, need to introduce the JAR package 2). Configuration Applicationcontext.xml file a. constraint file B that introduces AOP. Declares a slice (in fact, defines a bean node, class is a slice) c. Declares a slice configuration <aop:config>d. Defines a slice, which is equivalent to injecting a soul <aop:aspect id= "" ref= "" >e. Declaring pointcuts <aop:pointcut id= "" expression= "> Specify which of the items as the pointcut F. Define the notification <aop:before pointcut-ref= "method=" > Injection pointcut, declaring which method to be notified 2. Annotated mode implementation 1). SPRINGAOP programming, need to introduce the JAR package 2). Configuration Applicationcontext.xml file a. constraint file B that introduces AOP. Declares a Slice object/Declaration Interface implementation Class object <bean>c./** adds a slice to the class */@Aspect//Indicates defined in the Spring container: <aop:aspect id= "AA" ref= "Security" >d. DECLARE pointcut @pointcut (value= "Execution (* cn.itcast.f_aspectJ.a_before. Userserviceimpl.saveuser (..)) ") public void Save () {};e. Add notification @afterreturning (value= "Save () | | | find ()", returning= "ReturnValue") 3. Detailed notice 1). Any notification method can define the first parameter as the Org.aspectj.lang.JoinPoint type (* Surround notification needs to define the first parameter as the Proceedingjoinpoint type, which is a subclass of Joinpoint) 2). Pre-notification (before): Before accessing the target object method, perform the method feature of the notification definition: If the method (notification) in the proxy object (slice) throws an exception, the target object 3 is not executed at this time. Post-Notification (after-returning): After accessing the target object method, the method of executing the notification definition features: 1: If an exception is thrown in the target object, then notification 2 is not performed: Because the method in the target object is executed first, and then the notification is executed, it is possible to get theThe return value of the method of the target object? The first step: define in the Spring container: returning= "returnvalue" second step: In the method of the notification of the second parameter, you can specify the object type 4).  Exception notification: When an exception is thrown in the target object method after the target object method is accessed, the method feature of the notification definition is executed: 1: Notification is only executed when an exception is thrown in the target object method 2: Catch exception in the notification method first step: Define the second step in the Spring container: The position of the second parameter in the method of notification can be specified, for example, public void checksecurity (Joinpoint joinpoint,throwable Throwingvalue) {* Requirement one: Gets the parameter of the exception thrown by the target object to be placed in the position of the second parameter * requires two: type must specify Throwable type * requires three: Throwable corresponding attribute value to be defined in the spring container throwing = "Throwingvalue" value to match 5). Final notification: After accessing the target object method, regardless of whether or not an exception is thrown, the method of the notification definition is executed. Feature: 1: Method 6 for notification is executed regardless of whether the target object throws an exception. Surround notification: A. The last kind of notification is surround notification. Surround notifications are executed before and after a target object method executes. It gives the notification a chance B. Run before and after a method is executed. And it can determine when the method is executed, how it is executed, and even whether it executes. Surround notifications are often used in a thread-safe environment where you need to share a state before and after a method executes. Please try to use the simplest notification that meets your needs. (for example, do not use surround notifications if simple pre-notifications are available)
Pointcut Expressions (expression)
1). In fact execution method full name, 5 parameters: Band? Number denotes non-mandatory execution (Modifiers-pattern? Ret-type-pattern Declaring-type-pattern? Name-pattern (Param-pattern) Throws-pattern?) 2). Example: Execution of any common method: Execution (Public * * (.. ) Any of the execution of a method whose name begins with "Set": Execution (* set* (. )) Accountservice the execution of any method defined by the interface: Execution (* com.xyz.service.accountservice.* (. ) The execution of any method defined in the service package: Execution (* com.xyz.service.*.* (. ) Focus: Execution of any method defined in the service package or its child packages: execution (* com.xyz.service). *.*(.. ) Summary: * represents all, can be understood as a wildcard * (..) represents all Methods save* (*,string) represents a method that starts with Save, the first argument is any type, the second argument is a String type

Spring+jdbc
JDBC Programming features static code + Dynamic variable = JDBC Programming. In spring, dynamic variables can be given in the form of injections. This way of programming is suitable for packaging into templates. Static code forms a template, while a dynamic variable is a parameter that needs to be passed in JdbcTemplate encoding 1. Guide package in spring dependent packages and core packages for com.springsource.org.apache.commons.dbcp-1.2.2.osgi.jarcom.springsource.org.apache.commons.pool-1.5.3 . jarcom.springsource.org.junit-4.7.0.jarmysql-connector-java-5.0.8-bin.jarspring-jdbc-3.2.0.release.jarspring-tx-3.2.0.re Lease.jar2. Configuring DBCP Connection Pooling <!--configuration in Applicationcontext.xml dbcp connection pool-<bean id= "DataSource" class= " Org.apache.commons.dbcp.BasicDataSource "destroy-method=" Close "><property name=" Driverclassname "value=" Com.mysql.jdbc.Driver "></property><property name=" url "value=" jdbc:mysql://localhost:3306/testspring ? Useunicode=true&amp;characterencoding=utf8 "></property><property name=" username "value=" root " ></property><property name= "Password" value= "root" ></property><!--initial value when connection pooling starts-->< Property Name= "InitialSize" value= "1"/><!--the maximum value of the connection pool--><property name= "maxactive" value= "500"/><!--maximum idle value. After a peak time, the connection pool can slowly release a portion of the connection that has not been used, and has been reduced to maxidle until--><property name=" Maxidle "value=" 2 "/ ><!--Minimum idle value. When the number of idle connections is less than this value, the connection pool will pre-request some connections to avoid the performance overhead of--><property name= "Minidle" value= "1"/>3 in case of peak flooding. Inject Accountdao Properties <!--Create DAO objects--<bean id= "Accountdao" class= "Cn.itcast.b_crud. Accountdaoimpl "> <property name=" jdbctemplate "ref=" JdbcTemplate "></property> </bean><!- -Create a spring-provided JDBC template to manipulate the database--<bean id= "JdbcTemplate" class= "Org.springframework.jdbc.core.JdbcTemplate" > <property name= "dataSource" ref= "DataSource" ></property> </bean>4. manipulating databases in DAO private JdbcTemplate jdbctemplate; Cud using the Udpate method, the Query method #spring integration JUnit, complete test 1. Import? org.springframework.test-3.0.2.release.jar2. Add annotations, @RunWith (value=springjunit4classrunner.class) @ContextConfiguration (value= "classpath:cn/itcast/b_crud/ Beans.xml ") 3. @Resource (name= "Accountdao")

Spring facet-oriented Programming AOP (II)

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.