AOP aspect-oriented programming, can be said to be the perfect complement of OOP, it is well known that the object-oriented programming features are encapsulation inheritance and polymorphism, constructs an object hierarchy, can organize the code well, through the inheritance relationship to implement code reuse, But there will always be some repetitive code in the program is not very convenient to use inheritance to reuse and manage them, the function of the code is repeated and needs to be used in different places, although it can be encapsulated as a public function, but in such a display call is not very convenient.
AOP is able to extract repetitive code out of its own maintenance, and the common submodule has no alternative to invoking a direct hard call, compared to designing a common submodule, and AOP handles this type of problem with a flexible approach.
AOP divides a software system into two parts: core concerns and crosscutting concerns. The main process of business process is the core concern, and the part that has little relation is the crosscutting concern. one feature of crosscutting concerns is that they often occur in many of the core concerns and are essentially similar everywhere. such as permission authentication, logging, transaction processing. The role of AOP is to separate the various concerns in the system, separating the core concerns from the crosscutting concerns.
AOP Usage Scenarios:
AOP is used to encapsulate crosscutting concerns, which can be used in the following scenarios :
Authentication Permissions
Caching Cache
Context passing content delivery
Error handling errors handling
Lazy loading lazily loaded
Debugging Commissioning
Logging, tracing, profiling and monitoring record tracking optimization calibration
Performance optimization performance optimization
Persistence Persistence
Resource Pooling resource pool
Synchronization Synchronization
Transactions Transactions
some concepts related to AOP:
aspect (aspect): A focus of modularity, the implementation of this focus may be additional crosscutting multiple objects, such as transaction management. is implemented using Spring 's Advidor or interceptors.
connection point (joinpoint): An explicit point in the execution of a program, such as a call to a method or a particular exception being thrown.
notification (advice): The action performed by the AOP frameworkat a specific connection point .
pointcut (pointcut): Specifies a collection of connection points to which a notification will be raised.
Introduce (introduction): Add a method or field to the class being notified.
target Object: The object that contains the connection point, also known as the object being notified or proxied. Pojo
AOP proxy:an AOP framework-created object that contains notifications, in Spring ,an AOP agent is typically a JDK dynamic agent or cglib Agent.
Weaving (weaving): Assembling aspects to create a notified object. This can be done at compile time (for example, with the AspectJ compiler), or at run time. Spring, like other pure Java AOP frameworks, completes weaving at run time.
how Spring uses AOP:
first, direct use Proxyfactory to programmatically use Spring AOP, the proxyfactory provides a way to set the target object and eventually GetProxy method gets the proxy object. There is no explanation here.
Second, the configuration XML file in four ways:
1, configuration proxyfactorybean, explicitly set Advisors,advice, Target and so on
2, configuration autoproxycreator, in this way, or as before, using the defined bean, but obtained from the container is actually a proxy object
3, through <aop:config> to configure
4. Configureby <aop:aspectj-autoproxy> , use aspectj annotations to identify notifications and pointcuts
Xml through <aop:config> Implementation Example:
Dependent Spring-context will introduce core beans context aoplliance AOP commons-logging expression package to use AOP The Aspectjweaver package also needs to be introduced .
Define interfaces:
Public Interface {voidbuyapple ();}
Implementation class:
public class Youimpl implements-{public void Buyapple () {System.out.println ("Buy Apple! "); }}
Crosscutting Concerns:
public class Me {public void beatyou () {System.out.println ("punch you! "); } public void Giveyoucandy () {System.out.println ("give you sugar! "); }}
Configuration file:
<?xml version = "1.0" encoding= "UTF-8"? ><beansxmlns= "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-4.1.xsd "> <bean id= "Youimpl" class= "Com.gg.test.aop.YouImpl" ></bean> <bean id= "Me" class= "Com.gg.test.aop.Me" ></BEAN>&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;<AOP: Config> <aop:aspect id= "Me" ref= "Me" > &lT;aop:pointcutid= "Addmethod" expression= "Execution (*com.gg.test.aop.you.* (..))" /> <aop:before method= "Beatyou" pointcut-ref= "Addmethod" /> < Aop:after method= "Giveyoucandy" pointcut-ref= "Addmethod" /> </aop:aspect> </aop:config></beans>
Test:
public class Test {public static void main (string[] args) {ApplicationContext applicationcontext = new ClassPath Xmlapplicationcontext ("Aopdemo.xml"); you = (you) Applicationcontext.getbean ("Youimpl"); You.buyapple (); }}
Results:
650) this.width=650; "Src=" https://s1.51cto.com/wyfs02/M00/9D/F5/wKiom1mJWpWTl1l5AACJqZPzk9Q575.png-wh_500x0-wm_ 3-wmp_4-s_2455320876.png "title=" Q1.png "alt=" Wkiom1mjwpwtl1l5aacjqzpzk9q575.png-wh_50 "/>
by configuring Proxyfactorybean Implementation Example:
To implement a pre-enhanced interface:
public class Hijackbefore implementsmethodbeforeadvice{public void before (method, object[] args, Object target) Throws Throwable {System.out.println ("punch you! "); }}
Configuration file:
<?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-4.1.xsd "> <bean id= "Youimpl" class= "Com.gg.test.aop.YouImpl" ></bean> <!-- Define bean --> <bean id= "Hijackbeforebean" class= "for Hijacking class" Com.gg.test.aop.HijackBefore " /> <!--Create proxy --> < Bean id= "Youproxy" class= "Org.springframeWork.aop.framework.ProxyFactoryBean "> <property name=" target " ref = "Youimpl" /> <property name= "Interceptornames" > <list> <value>hijackBeforeBean</value> </list> </property> </bean></ Beans>
Test:
public class Test {public static void main (string[] args) {ApplicationContext ApplicationContext = Newclasspathx Mlapplicationcontext ("Aopdemo.xml"); Youproxy = (You) Applicationcontext.getbean ("Youproxy"); Youproxy.buyapple (); }}
Test results:
650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M02/9D/F5/wKiom1mJWsnzkTelAACDDSzqPoo510.png "title=" A2.png "alt=" Wkiom1mjwsnzktelaacddszqpoo510.png "/>
Examples are implemented through the advisor:
If the demand changes: you go to buy apples. I hit you on the road, I don't beat you when I buy bananas.
Notice Advice is a facet (Aspect) provided by Spring. But its function is too simple, can only
The facets are woven into all target methods of the target class and cannot be completed to weave the facets into the specified target method.
Consultant The Advisor is another facet that Spring provides. It can be used to perform more complex facets weaving functions. Pointcutadvisor is one of the advisors that can specify a specific entry point. The consultant wraps the notice and weaves the slices into different pointcuts at different points in time, depending on the type of notification.
public interface {void Buyapple (); void Buybunana ();}
public class Youimpl implements-{public void Buyapple () {System.out.println ("Buy Apple! "); } public void Buybunana () {System.out.println ("Buy Bananas! "); }}
To implement a pre-enhanced interface:
Public Classhijackbefore implements methodbeforeadvice{public void before (Method method,object[] args, Object target) t Hrows throwable {System.out.println ("punch you! "); }}
Configuration file:
<!--1.*:namematchmethodpointcutadvisor Name matching method pointcut Advisor --> <!-- Facets: Consultant Consultant (Advisor) to package Notice (Advice)--> <bean id= " Beforeadvisor "class=" Org.springframework.aop.support.NameMatchMethodPointcutAdvisor "> <property name= "Advice" ref= "Beforeadvice" ></property> <!--Specifies the method to be enhanced: This is the Buyapplet () method, and the Buybunana () method does not enhance --> <propertyname= "MappedName" value= "buyApple ></property> <!-- You can also use Mappednames to specify multiple methods <propertyname= "Mappednames" value= "DoFirst,doSecond" ></property> --> </bean > <!--*********************************************** --> <!-- 2.*:RegexpMethodPointcutAdvisor Regular Expression matching method entry-point advisor --> <!-- Facets: consultant Advisor (advisor) to wrap Notifications (Advice) --> <!-- <bean id= "Beforeadvisor" class= " Org.springframework.aop.support.RegexpMethodPointcutAdvisor "> <property name= "Advice" ref= "Beforeadvice" ></property> <property name= "pattern" value= ". *dof.*t" ></property> </bean> -->
Test:
public class test{public static void Main (string[] args) {ApplicationContext applicationcontext = new CLASSPATHXM Lapplicationcontext ("Aopdemo.xml"); Youproxy = (You) Applicationcontext.getbean ("Youproxy"); Youproxy.buyapple (); Youproxy.buybunana (); }}
Test results:
650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M02/9D/F5/wKioL1mJWuOg0ulLAACF2KwY4BA070.png "title=" Q3.png "alt=" Wkiol1mjwuog0ullaacf2kwy4ba070.png "/>
Summarize:
The AOP agent in Spring is generated and managed by the spring IOC container, and its dependencies are managed by the IOC container. Therefore,the AOP Proxy can use the other bean instances in the container directly as a target, a relationship that can be provided by the dependency injection of the IOC container.
the rules for creating a proxy for Spring are:
1. Use the Java dynamic Agent to create an AOP proxyby default , so that you can create proxies for any interface instances
2, when the class that needs the proxy is not the proxy interface,Spring switches to use the CGLIB proxy, or it can force the use of CGLIB
AOP the key to programming is defining pointcuts and defining enhanced processing, once the appropriate pointcuts and enhancements have been defined, AOP the framework will automatically generate AOP Agent , that is, the method of the proxy object = Enhanced processing + method of the Proxied object.
Spring-oriented tangent programming