Spring IOC and AOP principles thoroughly understand

Source: Internet
Author: User
Tags aop modifiers throwable

Article about spring in this blog: Spring IOC and AOP principles, Spring Transaction Principles, spring configuration file properties, and agent patterns in spring


Spring provides a collection of tools for lightweight application development practices that exist in spring in the form of interfaces, abstract classes, or tool classes. By using these toolset, you can implement friendly integration between your application and various open source technologies and frameworks. For example, the data Access tool in the JDBC package, Spring JDBC, the Spring test package for writing unit tests and Spring-mock, Spring script to access the dynamic scripting language, and also the tools for sending Mail Spring Mail, Schedule and task processing tools spring scheduling. It can be said that most of the common issues that are often involved in enterprise application development can be easily addressed through some of the utility kits provided by spring

Three modes of Dependency injection: (1) interface Injection (2) construct injection (3) Setter injection

Control reversal (IoC) is the same concept as Dependency injection (DI), the purpose of introducing IoC is: (1) to remove and reduce the coupling between classes, (2) to advocate interface programming, to implement the principle of dependency switching, (3) to improve the system can be inserted, testable, modifiable and other characteristics.
The practice is as follows: (1) The dependency relationship between the beans is as much as possible as an association relationship;
(2) To convert the association of the specific class as much as possible to the Java Interface Association, rather than to the specific service object;
(3) The instance of which implementation class of the relevant Java interface is associated with the bean instance, described in the metadata of the configuration information;
(4) by the IOC component (or container), the specific Bean class is instantiated and the dependencies between the beans are injected in according to the configuration information.

The Org.springframework.beans and Org.springframework.context packages are the foundation of the spring IOC container. The advanced configuration mechanism provided by beanfactory makes it possible to manage objects of any nature. ApplicationContext is an extension of the beanfactory, and features are further enhanced, such as easier integration with spring AOP, message resource processing (international processing), event delivery, and context implementations of various application tiers ( such as Webapplicationcontext for Web applications). In short, Beanfactory provides a configuration framework and basic functionality, while ApplicationContext adds more functionality to support the core content of the enterprise. ApplicationContext is completely extended by beanfactory, so the ability and behavior of beanfactory is also applicable to ApplicationContext.

The IOC container is responsible for hosting the bean and managing the bean. In spring, Beanfactory is the core interface of the IOC container. Its responsibilities include instantiating, locating, configuring objects in an application, and building dependencies between those objects. Spring provides us with a lot of easy-to-use Beanfactory implementations, Xmlbeanfactory is one of the most common. The implementation will describe in XML the objects that make up the application and the dependencies between objects. The Xmlbeanfactory class will hold this XML configuration metadata and use it to build a fully configurable system or application.

To implement a container:

Resource Resource = new Filesystemresource ("Beans.xml");
Beanfactory factory = new Xmlbeanfactory (resource);
... Or ...
Classpathresource resource = new Classpathresource ("Beans.xml");
Beanfactory factory = new Xmlbeanfactory (resource);
... Or ...
ApplicationContext context = new Classpathxmlapplicationcontext (
        new string[] {"Applicationcontext.xml", " Applicationcontext-part2.xml "});
Course, an applicationcontext are just a beanfactory
beanfactory factory = (beanfactory) context;
It is useful to split an XML configuration file into multiple parts. To load multiple XML files to generate a ApplicationContext instance, you can pass the file path as an array of strings to the ApplicationContext constructor. The Bean Factory will read the bean definition from multiple files by invoking the bean defintion reader. In general, the spring team tends to do this because each configuration does not find a combination of them with other configuration files. Another approach is to use one or more <import/> elements to load the bean definition from another file or multiple files. All <import/> elements must be placed before the <bean/> element to complete the import of the bean definition. Let's look at an example:
<beans><import resource= "Services.xml"/> <import resource= "Resources/messagesource.xml
    "/>
    <import resource= "/resources/themesource.xml"/> <bean id= "bean1" class= "
      ..."/> <bean
    Id= "bean2" class= "..."/>
  </beans>
In the above example, we load the bean definition from 3 external files: Services.xml, Messagesource.xml, and Themesource.xml. All of these are relative paths, so in this case the services.xml must be placed in the same directory or classpath as the import file, and the file locations of Messagesource.xml and Themesource.xml must be placed in the same directory as the import file. Resources directory. As you can see, the beginning of the slash '/' is actually negligible. So it might be better not to slash '/'. Depending on the schema (or DTD) of the spring XML configuration file, the imported file must be a fully valid XML bean definition file, and the root node must be a <beans/> element.
The difference between beanfactory and Factorybean, in short, beanfactory is loading the container, loading all the beans, while the factorybean is used to create the proxy class
=============================================================== the above mentioned beanfactory its responsibilities include: instantiation, positioning, Configure the objects in the application and build dependencies between them. Factorybean (typically, a bean does not have to implement Factory mode itself, the spring container acts as a factory, but in a few cases the bean in the container itself is the factory, which produces other bean instances), and the effect is to produce other bean instances. Typically, there is no particular requirement for this bean, and only one factory method is required, which is used to return other bean instances. Other bean instances produced by the factory Bean are no longer produced by the spring container, so unlike the normal bean configuration, the class element is no longer required.
Proxyfactorybean is used to create proxies (based on the bean that the advisor generates, that is, the Targetbean agent) our advisor,pointcut and so on, the ultimate goal is to create this agent. =============================================================== The following will be mentioned

AOP Full name aspect-oriented programming, the Chinese literal translation for aspect-oriented programming, has become a more mature programming idea, can be used to solve the application system distributed in the various modules of the cross-cutting concerns. In the lightweight Java EE application development, the use of AOP to flexibly handle some of the crosscutting nature of the system-level services, such as transaction processing, security checks, caching, object pool management, etc., has become a very suitable solution. The more important concepts in AOP are: Aspect, Joinpoint, Ponitcut, Advice, Introduction, Weave, Target object, Proxy object, etc.

An introduction (Introduction) is the addition of a method or field property to an existing class, which enables you to implement a new interface for an existing Java class without changing the existing class code, or to assign it a parent class for multiple inheritance. An introduction (Introduction) is used to change the static structure of a class relative to the enhancement (Advice) that dynamically alters the function or process of a program. For example, we can make an existing interface for implementing java.lang.Cloneable, so that we can replicate instances of this class through the Clone () method.

The interceptor is used to intercept the connection points, thereby adding the custom slice module function before or after the connection point. In most Java AOP framework implementations, interceptors are used to implement field access and method invocation interception (interception). Multiple interceptors acting on the same connection point form a chain of connectors (interceptor chain), and each interceptor on the link usually calls the next interceptor. The Spring AOP and Jboos AOP implementations are implemented using interceptors.

Object-oriented programming (OOP) solves the problem with the focus on the abstraction of specific domain model, and the key point of aspect programming (AOP) is the abstraction of the focus. That is, some common problems in the system that need to be dispersed across a number of unrelated modules are addressed by AOP; AOP can use a better way to solve crosscutting concerns and related design challenges that OOP does not do well to achieve loose coupling. Therefore, aspect-oriented programming (AOP) provides another way of thinking about the structure of the program, which is an extension of OOP, to make up for the inadequacy of OOP.


AOP Concepts: Note The following example <AOP: The beginning of the ASPECTJ concept, spring is not divided so thin.

-Aspect (Aspect): A focus of the modularity, this focus implementation may be another crosscutting multiple objects. Transaction management is a good example of crosscutting concerns. Aspect is implemented with spring's advisor or interceptor, which can then be configured by @aspect annotations or in Applictioncontext.xml:

<aop:aspect id= "Fouradviceaspect" ref= "Fouradvicebean" order= "2" >

-Connection point (Joinpoint): The behavior of the program during execution, such as the invocation of a method or a particular exception is thrown, there are joinpoint classes and Proceedingjoinpoint classes in the code, as shown below, you can get many parameters by Joinpoint,  Joinpoint is generally used as a parameter in the advice implementation method, Proceedingjoinpoint is used to implement parameter passing around advice. The proxy object and target object can be seen through joinpoint through the Joinpoint interface below.

Package Org.aspectj.lang;
Import org.aspectj.lang.reflect.SourceLocation;
Public interface Joinpoint {
    String toString ();         Related information for the location of the connection point
    String toshortstring ();     Short related information for the location of the connection point
    String tolongstring ();     All relevant information about the location of the connection point
    Object getthis ();         Returns the AOP proxy object
    gettarget ();       Returns the target object
    object[] Getargs ();       Returns the notification method parameter list
    Signature getsignature ();  Returns the current connection point signature
    sourcelocation getsourcelocation ();//Returns a
    String Getkind () in the class file where the connection point method is located;        Connection point type
    staticpart getstaticpart ();//return connection point static part
} public

Interface Proceedingjoinpoint extends Joinpoint {public
    Object proceed () throws Throwable;
    Public Object Proceed (object[] args) throws Throwable;
}

-Pointcut (Pointcut): Specifies a collection of connection points that a Adivce will be thrown. An AOP framework must allow developers to specify pointcuts, for example, using regular expressions.

Configuration in XML:

<aop:pointcut id= "mypointcut" expression= "Execution (* com.wicresoft.app.service.impl.*.* (..))" method= "release" />

Or use annoation: @pointcut ("Execution * transfer (..)") With a return value of void, the method body is empty to name the pointcut such as: private void Anyoldtransfer () {}

It can then be referenced in advice, such as: @AfterReturning (pointcut= "Anyoldtransfer ()", returning= "ReVal")

Package ORG.SPRINGFRAMEWORK.AOP;
    Public interface Pointcut {classfilter getclassfilter ();
    Methodmatcher Getmethodmatcher ();
Pointcut TRUE = truepointcut.instance;
} package ORG.SPRINGFRAMEWORK.AOP; Public interface Classfilter {Boolean matches (class<?> clazz);//If Clazz is true when it matches the phenomenon we are concerned about, return false CLASSF Ilter TRUE = trueclassfilter.instance;//static parameter if the type does not matter for the pointcut to be caught, pass this parameter to Pointcut} package
ORG.SPRINGFRAMEWORK.AOP;

 Public interface Methodmatcher {Boolean matches (method method, class<?> Targetclass); /** * Whether the value of the parameter is sensitive * If False indicates that the parameter value (not sensitive to the parameter value) is not needed for the match, which is called Staticmethodmatcher, then only * matches (method method, Class<?> t Argetclass);
  Is executed, the execution result can be cached has increased efficiency. * If True indicates that a match is required to determine the value of the parameter (the parameter value is sensitive), called Dynamicmethodmatcher, then first executes the * matches (method method, class<?> Targetclass); If true, then the * Boolean matches (method method, Class<?> Targetclass, object[] args) are then executed; * * */Boolean is
 Runtime (); Boolean matches (method method, Class<?>
 Targetclass, object[] args);
Methodmatcher TRUE = truemethodmatcher.instance; }

A description of the execution used in Pointcut:

Execution (Modifiers-pattern ret-type-pattern declaring-type-pattern name-pattern (param-pattern) Throws-pattern?)

Modifiers-pattern: The operation permission of the method

Ret-type-pattern: Return value

Declaring-type-pattern: The package where the method resides

Name-pattern: Method Name

Parm-pattern: Name of parameter

Throws-pattern: Exception

The memory rule is when Java defines a method: public boolean producevalue (int oo) throws Exception, just add the package name to the method name.

Among them, except Ret-type-pattern and Name-pattern, the other is optional. In the example above, execution (* com.spring.service.*.* (..)) Indicates that the return value is any type under the Com.spring.service package, any method name is arbitrary, and any method that the parameter does not limit. Common pointcut structure diagram:


-Notification (Advice): The actions that the AOP framework performs at a particular connection point. Various types of notifications include "around", "before", and "throws" notifications. The notification type is discussed below. Many of the AOP frameworks include spring as a notification model for interceptors, maintaining a chain of interceptors around the connection points. Pointcut must be used in advice

Configured in XML, the method in the configuration is the aspect implementation class, using the Pointcut custom or Pointcut-ref to refer to the Pointcut

<aop:before pointcut= "Execution (* com.wicresoft.app.service.impl.*.* (..))" method= "authority"/>

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.