Spring3 actual Combat first chapter AOP facets XML configuration

Source: Internet
Author: User

Just read the first chapter of Spring3 Real-time books. I didn't pay attention to it before. Now see the test

Aop

AOP (Aspect oriented programming), which is aspect-oriented programming, can be said to complement and refine OOP (object oriented programming, OO programming). OOP introduces concepts such as encapsulation, inheritance, and polymorphism to create an object hierarchy that simulates a collection of public behavior. However, OOP allows developers to define vertical relationships, but it is not appropriate to define landscape-like relationships, such as logging capabilities. The log code tends to spread horizontally across all object hierarchies, and it has nothing to do with the core functionality of the object it corresponds to, such as the persistence of other types of code, such as security, exception handling, and transparency, the extraneous code scattered around is called crosscutting (cross Cutting), in the OOP design, It leads to a lot of duplication of code and is not conducive to the reuse of individual modules.

AOP technology, on the contrary, uses a technique called "crosscutting" that splits the encapsulated object interior and encapsulates public behavior that affects multiple classes into a reusable module, named "Aspect", or tangent. The so-called "cut-off", simply said to be those unrelated to the business, but for the business module calls together the logic or responsibility to encapsulate, easy to reduce the system duplication of code, reduce the coupling between modules, and conducive to future operability and maintainability.

Using "crosscutting" techniques, AOP divides software systems 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 similar everywhere, such as authority authentication, logging, and things. The role of AOP is to separate the various concerns in the system, separating the core concerns from the crosscutting concerns.

AOP Core Concepts

1. Cross-cutting concerns

What methods to intercept and how to deal with them, these concerns are called crosscutting concerns.

2. Slice (aspect)

A class is an abstraction of an object's characteristics, and a facet is an abstraction of a crosscutting concern.

3, Connection point (Joinpoint)

The point that is intercepted, because spring only supports connection points of the method type, so the connection point in spring refers to the method being intercepted, in fact the connection point can also be a field or a constructor

4. Entry point (pointcut)

Definition of interception of connection points

5. Notice (advice)

The so-called notification refers to the interception to the connection point after the code to execute, the notification is divided into pre-, post-, exception, final, surround notification five categories

6. Target Object

Target object for the agent

7. Weave in (weave)

The process of applying a slice to the target object and causing the proxy object to be created

8. Introduction (Introduction)

Without modifying the code, the introduction can dynamically add some methods or fields to the class at run time

Spring's support for AOP

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 proxy by 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 programming is actually a simple thing, and throughout AOP programming, programmers only need to participate in three parts:

1. Define Common business components

2, define pointcuts, a pointcut may cross-cutting multiple business components

3, the definition of enhanced processing, enhanced processing is the AOP framework for ordinary business components to weave the processing action

So the key to AOP programming is defining pointcuts and defining enhanced processing, and once the appropriate pointcuts and enhancements are defined, the AOP framework automatically generates an AOP proxy, the method of the Proxy object = The method of enhancing processing + the Proxied object .

Simple implementation of AOP based on spring

Note, before you explain, that using spring AOP, it is not enough to run the code successfully, only the jar package provided by spring to the developer, please download two additional jar packages on the Internet:

1, Aopalliance.jar

2, Aspectjweaver.jar

Define an interface first

Package Com.spring;public Interface SPRINGAOP {        void Show ();}  

Then define an implementation class

Package Com.spring;public class Springaopim implements SPRINGAOP {public        void Show () {                System.out.println ("Start");}            }   

Then there is a crosscutting class

Package Com.spring;public class minstrel  {public    void Start () {        System.out.println (" Pre-notification ");    }            public void End () {        System.out.println ("Post-Notification");}}     

Finally, an XML 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:context= "Http://www.springframework.org/schema/context"
xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx"
Xsi:schemalocation= "Http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
Http://www.springframework.org/schema/context
Http://www.springframework.org/schema/context/spring-context-3.0.xsd
Http://www.springframework.org/schema/aop
Http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
Http://www.springframework.org/schema/tx
Http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
<bean id= "Minstrel" class= "Com.spring.Minstrel"/> <!--definition Bean crosscutting class--
<bean id= "Show" class= "Com.spring.SpringAopIm"/> <!--define Bean Interface implementation Class--
<aop:config>
<aop:aspect id= "Time" ref= "Minstrel" ><!--Reference crosscutting class--
<aop:pointcut id= "Addallmethod" expression= "Execution (* com.spring.SpringAopIm.show (..))"/><!--crosscutting method Com.spring.SpringAopIm is the path of a class that can be substituted with * instead of show is the method in the class can be replaced by the (..) is the parameter of the method--
<aop:before method= "Start" pointcut-ref= "Addallmethod"/><!--pointcut-ref refer to the ID name of the Crosscutting method method= "Start" The method name for the predecessor notification can be customized--
<aop:after method= "End" pointcut-ref= "Addallmethod"/><!--pointcut-ref refer to the ID name of the crosscutting method method= "Start" The method name for the post notification can be customized--
</aop:aspect>
</aop:config>
</beans>

and write a test test.

Package com.spring;import org.junit.test;import org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;public class minstreltest {    @Test Public    void Show () {ApplicationContext context = new Classpathxmlapplicationcontext ("Spring.xml");//Get XML SPRINGAOP bean = (SPRINGAOP) Context.getbean ("Show"); Getting the name of the bean Bean is the custom in the bean ID XML that you need to cross-cut because SPRINGAOPIM implements the SPRINGAOP interface, so the cast must be SPRINGAOP bean.show () with the parent class; Call Method }}      

Final display Results

October 12:08:04 Morning org.springframework.context.support.AbstractApplicationContext Preparerefresh Info: refreshing org[email protected]6bb9db06:startup Date [Sun Oct 00:08:04 CST]; root of the context hierarchy October 15, 12:08:04 Morning Org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadbeandefinitions info: Loading XML Bean definitions from class path resource [spring.xml] October 12:08:04 Morning Org.springframework.beans.factor Y.support.defaultlistablebeanfactory preinstantiatesingletons Info: pre-instantiating singletons in Org.s[email protected]ccd26df:defining Beans [Minstrel,show,org.springframework.aop.config.internalautoproxycreator, Org.springframework.aop.aspectj.aspectjpointcutadvisor#0, Org.springframework.aop.aspectj.aspectjpointcutadvisor#1, Addallmethod]; Root of factory hierarchy front notification start     

Attention:

Spring AOP, to run the code successfully, it is not enough to use only the jar package provided by spring to the developer, please download two additional jar packages on the Internet:

1, Aopalliance.jar

2, Aspectjweaver.jar

Citation http://www.cnblogs.com/hongwz/p/5764917.html thanks to the "originality" of the blog to benefit a lot

Spring3 actual Combat first chapter AOP facets XML configuration

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.