Spring Framework IOC container and AOP parsing

Source: Internet
Author: User
Tags aop connection pooling

I. Introduction to the spring Open source framework

II. Spring under IOC container and Di (Dependency Injection Dependency injection)

Three, spring-oriented aspect programming (AOP) and transaction management configuration

I. Introduction to the spring Open source framework

  Spring is an open source framework, and spring is a lightweight Java development framework that emerged in 2003 by Rod Johnson in his book expert one-on-one development and Some of the concepts and prototypes elaborated in design are derived. It is created to address the complexities of enterprise application development. Spring uses basic JavaBean to accomplish things that were previously only possible by EJBS. However, the use of spring is not limited to server-side development. From the standpoint of simplicity, testability, and loose coupling, any Java application can benefit from spring. in short, spring is a lightweight control inversion (IoC) and aspect-oriented (AOP) container framework.

 Spring's basic framework consists of six major modules: DAO, ORM, AOP, JEE, WEB, CORE

Spring DAO: Spring provides operational support for JDBC: The JdbcTemplate Template Tool class.

Spring orm: Spring can be integrated with the ORM framework. For example, Spring integrates the Hibernate framework, where spring also provides the Hibernatedaosupport tool class, which simplifies hibernate operations.

Spring Web: Spring provides support for struts, SPRINGMVC, and web development. At the same time, spring itself offers an MVC-based solution.

Spring AOP: Spring provides aspect-oriented programming that provides transaction management for a layer, such as adding thing control to the service layer.

Spring JEE: Support for the Java EE Development specification, such as EJB.

Spring Core: Provides the creation and processing of dependent object relationships for IOC container objects.

II. Spring under IOC container and Di (Dependency Injection Dependency injection)

  IOC container : is a container with dependency injection capability, is a container that can create objects, the IOC container is responsible for instantiating, locating, configuring objects in the application, and establishing dependencies between those objects. Usually new one instance, control is controlled by the programmer, and "control inversion" means that the new instance work is not done by the programmer but is given to the spring container. Beanfactory is the actual representative of the IOC container in spring.

  DI(Dependency Injection Dependency Injection) : Handles object dependencies after the container has created the object.

The injection method of dependency injection spring:

        • Set Injection mode
        • Static Factory Injection method
        • Construction Method Injection Mode
        • Annotation-based approach

1. Set Injection method:

Control Layer Code:

Private Orderserviceimp OrderService;    public void Setorderservice (Orderserviceimp orderservice) {       this.orderservice = OrderService;}

Spring configuration XML File: Where the configuration declares the Orderaction class exists with the attribute OrderService. When the program runs, it injects the OrderService object that has been instantiated into the Setorderservice mode.

<bean name= "orderaction" class= "com.pec.action.OrderAction" >        <property name= "OrderService" ref= " OrderService "></property></bean><bean name=" OrderService "class=" Com.pec.service.imp.OrderServiceImp "></bean>

2. Constructor Injection Method:

Control Layer Code:

Private Orderserviceimp OrderService;    Public orderaction (Orderserviceimp orderservice) {        this.orderservice = OrderService;    }

Spring Configuration XML file:

<bean name= "orderaction" class= "com.pec.action.OrderAction" >      <constructor-arg ref= "OrderService" > </constructor-arg></bean><bean name= "OrderService" class= "COM.PEC.SERVICE.IMP.ORDERSERVICEIMP" ></bean>

3, based on the annotation of the way (recommended use, more convenient and less configuration)

Control Layer Code:

@Autowired   OrderService;

Service Layer Code:

@Service ("orderservice") public class Orderserviceimp implements IOrderService {    @Autowired     Javaordermdao;    @Autowired    Javaorderddao;    @Override public    list<javaordermlist> findorderm (Ordersearch search) {        return Javaordermdao.findjavaorderm (search);    }    @Override public    list<javaorderdlist> findorderd (Ordersearch search) {        return Javaorderddao.findjavaorderd (search);}    }

DAO Layer Code:

@Repository ("Javaordermdao") public class Javaordermdaoimp extends Basehibernatedao<javaorderm, Serializable> implements Ijavaordermdao {...}
@Repository ("Javaorderddao") public class Javaorderddaoimp Extendsbasehibernatedao<javaorderd, Serializable> implements Ijavaorderddao {...}

Note the point:

⑴ persistence layer The DAO layer annotation repository specifies the name, and the declaration name must be consistent in the service layer.

⑵ services Layer Service Layer annotation service specifies the name, and the names declared in the control layer must be the same.

⑶ annotation Methods Inject dependency annotations:

@Component         Add the object to the IOC container, the object reference name is the class name, and the first letter lowercase @component ("name") assigns the specified name to the object, adding the IOC container @repository        Primarily used to identify objects that are joined to a container is a persistent layer of components (classes) @Service           primarily used to identify objects that are joined to a container is a component of a business logic layer @controller        is primarily used to identify the object that joins the container as a component of a control layer @resource          injection Attribute (DI), the object is injected into the @resource decorated object @autowired         injection Property (DI), the object is injected into the @autowired decorated object.

⑷ annotations can simplify configuration and improve development efficiency, but are also detrimental to post-maintenance.

Note: The difference between @Autowired and @resource

Three, spring-oriented aspect programming (AOP) and transaction management configuration

AOP is the vertical programming, such as Business 1 and Business 2 need a common operation, and to each business to add the same code, rather than write over the code, let two business common use of this piece of code. In the daily order management, commodity management, capital Management, inventory management and other business, will need to similar to logging , transaction control, Authority control, performance statistics, exception handling and transaction processing . AOP extracts all common code, places it centrally in place, and then dynamically weaves the common code into the container at run time.

AOP involves names:

Facets (Aspect): In fact, the realization of common functions. such as log plane, permission plane, transaction plane, and so on. In practice, a common Java class that holds common functionality implementations can be identified as facets by an AOP container, as specified in the configuration.

notification (Advice): is the specific implementation of facets. The target method is the reference point, depending on where it is placed, there are 5 kinds of pre-notification (before), post-notification (afterreturning), exception Notification (afterthrowing), final notification (after) and surround notification (Around). In practice, it is usually a method in a slice class, which is exactly what kind of notification, which is also specified in the configuration.

connection point (Joinpoint): The place where the program is able to insert slices during operation. For example, method invocations, exception throws, or field modifications, but spring supports only method-level connection points.

pointcut (Pointcut): Used to define which connection points the notification should be cut into. Different notifications often need to be cut into different connection points, and this exact match is defined by the regular expression of the pointcut.

target Object: The object that is about to cut into the plane, that is, the object that is being notified. All of these objects are left with clean core business logic code, and all common functionality code waits for an AOP container to cut in.

proxy Object: An object that is dynamically created after the notification is applied to the target object. It can be simply understood that the function of the proxy object equals the core business logic functionality of the target object plus the shared functionality. The proxy object is transparent to the user, and is the product of the process of running the program.

Weaving (Weaving): The process of applying facets to a target object to create a new proxy object. This process can occur in the compilation period, the class loading period and the operating period, of course, different points of occurrence have different preconditions. For example, in the compilation period, a special compiler is required to support this AOP implementation, and in the class loading period, a special class loader supporting AOP implementation is required, which can be implemented dynamically by the reflection mechanism of Java language and dynamic agent mechanism.

 

Spring uses AOP to configure transaction management consisting of three parts, namely the DataSource,TransactionManager , and proxy mechanisms , regardless of the configuration method, The general change is only part of the agency mechanism. DataSource, TransactionManager These two parts only according to the data access way change, for example uses Hibernate to carry on the data access, DataSource actually is sessionfactory, The implementation of TransactionManager is Hibernatetransactionmanager.

Spring transaction configuration Five ways: Each bean has a proxy, all beans share a proxy base class, use Interceptors, interceptors configured with the TX tag , full annotations

1 . Interceptor configured with TX tag

<!--4, configure hibernate properties-<!--introduce db.properties properties file--<bean class= "org.springframework.beans.factory.c Onfig. Propertyplaceholderconfigurer "> <property name=" Location "value=" Classpath:db.properties "></property > </bean> <!--configuration data sources, connection pooling using C3P0, see Hibernate official Documentation "Basic configuration section"-<bean id= "dataSource" class= "com . Mchange.v2.c3p0.ComboPooledDataSource "destroy-method=" Close "dependency-check=" None "> <property name = "Driverclass" > <value>${datasource.driverClassName}</value> </property> &lt ;p roperty name= "Jdbcurl" > <value>${datasource.url}</value> </property> <p Roperty name= "User" > <value>${datasource.username}</value> </property> <p Roperty name= "Password" > <value>${datasource.password}</value> </property> & Lt;property name= "AcquireiNcrement "> <!--c3p0 the number of connections fetched at one time when the connection in the connection pool is exhausted. Default:3-<value>${c3p0.acquireIncrement}</value> </property> <prope Rty name= "Initialpoolsize" > <!--the number of connections obtained at initialization, the value should be between Minpoolsize and Maxpoolsize. Default:3-<value>${c3p0.initialPoolSize}</value> </property> <proper Ty name= "Minpoolsize" > <!--the minimum number of connections that are kept in the connection pool. -<value>${c3p0.minPoolSize}</value> </property> <property name= "Maxpoo Lsize "> <!--the maximum number of connections that are kept in the connection pool. Default:15-<value>${c3p0.maxPoolSize}</value> </property> <property Name= "MaxIdleTime" > <!--maximum idle time, the connection is discarded if not used in 60 seconds. If 0, it will never be discarded. default:0-<value>${c3p0.maxIdleTime}</value> </property> <property N Ame= "Idleconnectiontestperiod" > <!--Check for idle connections in all connection pools every 60 secondsPick up. default:0-<value>${c3p0.idleConnectionTestPeriod}</value> </property> & Lt;property name= "Maxstatements" > <!--the standard parameters of JDBC to control the number of preparedstatements loaded within the data source. However, because the pre-cached statements belong to a single connection instead of the entire connection pool.                 So setting this parameter takes into account a variety of factors. If both maxstatements and maxstatementsperconnection are 0, the cache is closed.  default:0-<value>${c3p0.maxStatements}</value> </property> <property Name= "Numhelperthreads" > <!--c3p0 is asynchronous, slow JDBC operations are done by the help process. Extending these operations can effectively improve performance, and multiple operations are performed simultaneously through multithreading.    Default:3-<value>${c3p0.numHelperThreads}</value> </property> </bean> <!--configuration Sessionfactory--<bean id= "sessionfactory" class= "Org.springframework.orm.        Hibernate3.annotation.AnnotationSessionFactoryBean "> <property name=" dataSource "ref=" DataSource "> </property> <!--hibernate Settings--> <property name= "hibernateproperties" > <props> <prop key= "Hibernate.di Alect ">${hibernate.dialect}</prop> <prop key=" Hibernate.show_sql "> ${hibernate.show_sql} &lt                ;/prop> <prop key= "Hibernate.jdbc.fetch_size" >${hibernate.jdbc.fetch_size}</prop> <prop key= "Hibernate.jdbc.batch_size" >${hibernate.jdbc.batch_size}</prop> <prop key= "Hi Bernate.connection.release_mode ">${hibernate.connection.release_mode}</prop> <prop key=" Hiberna Te.format_sql ">${hibernate.format_sql}</prop> <prop key=" hibernate.connection.SetBigStringTryCl        OB ">true</prop> </props> </property> <!--anotation Annotations Scan entity class--            <property name= "Packagestoscan" > <list> <value>com.pec.model</value>   </list>     </property> </bean>      <!--5, Spring configuration declarative things-->          <!--configuration Transaction--<bean id= "TransactionManager" class= "Org.springframework.orm.hibernate3.HibernateTran        Sactionmanager "> <property name=" sessionfactory "ref=" Sessionfactory "></property> </bean> <!--configuring transactions range-<tx:advice id= "Txadvice" transaction-manager= "TransactionManager" > <tx:attr ibutes> <tx:method name= "get*" read-only= "false" propagation= "not_supported"/> <tx:meth OD name= "find*" read-only= "false" propagation= "not_supported"/> <tx:method name= "save*" propagation= "REQ Uired "/> <tx:method name=" update* "propagation=" REQUIRED "/> <tx:method name=" delete* "  propagation= "REQUIRED"/> <tx:method name= "create*" propagation= "REQUIRED"/> <tx:method     Name= "anscy*" propagation= "REQUIRED"/> </tx:attributes> </tx:advice> <!--defining facets--- <aop:config Proxy-target-class= "true" > <aop:pointcut id= "pointcut" expression= "Execution (* com.pec.service).  *.*(..))" /> <aop:advisor advice-ref= "Txadvice" pointcut-ref= "Pointcut"/> </aop:config>

There are a few points to note:

⑴pointcut in three "*", the first * represents the return value, the second * represents the service child package, the third * represents the method name, "(.. ) "represents a method parameter.

⑵ the pointcut at this point is configured at the service layer, the method name needs to be named at the beginning of the advice notification point.

⑶ in accordance with the prescribed naming method, will be controlled by the spring transaction, maintain the consistency of operations. For example, inserting 100 data into a database, the first 99 records are executed until the 100th error occurs, and the transaction control is rolled back to the initial state before execution.

2. Using Bean Proxy

<?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:tx= "Http://www.springframework.org/schema/tx" xmlns:aop= " Http://www.springframework.org/schema/aop "xmlns:context=" Http://www.springframework.org/schema/context "xmlns:      Mvc= "Http://www.springframework.org/schema/mvc" xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans-4.0.xsd Http://www.springframework.org/schema/context H Ttp://www.springframework.org/schema/context/spring-context.xsd Http://www.springframework.org/schema/tx http:/ /www.springframework.org/schema/tx/spring-tx-2.5.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP Http://www.sprin Gframework.org/schema/aop/spring-aop-2.5.xsd "default-autowire=" Default "> <!--<bean name=" Usermanage R "class=" Com.tgb.manager.UserManagerImpl "></bean> <bean name= "Usercontroller" class= "Com.tgb.web.UserController" > <property name= "Userma Nager "ref=" Usermanager "></property> </bean> <context:component-scan base-package=" Com.tgb . Dao "/> <context:component-scan base-package=" com.tgb.entity "/> <context:component-scan base-package=" Com.tgb.manager "/> <context:component-scan base-package=" Com.tgb.web "/> <!--Introducing properties in Init.properties --<bean id= "Placeholderconfig" class= "        Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer "> <property name=" Locations "> <list> <value>classpath:config/spring/jdbc.properties</value> </list> & Lt;/property> </bean> <!--configuration data source, connection pooling using C3P0, see Hibernate official Documentation "Basic configuration section"--<bean id= "Dataso Urce "class=" Com.mchange.v2.c3p0.ComboPooledDataSource "> <property name=" Driverclass"Value=" ${datasource.driverclassname} "></property> <property name=" Jdbcurl "value=" ${datasource.url} " ></property> <property name= "user" value= "${datasource.username}" ></property> <prope Rty name= "Password" value= "${datasource.password}" ></property> </bean> <!--configuration Sessionfactory- -<bean id= "sessionfactory" class= "Org.springframework.orm.hibernate4.LocalSessionFactoryBean" > &LT;PR Operty name= "DataSource" ref= "DataSource"/> <property name= "hibernateproperties" > <props&gt                ; <prop key= "Hibernate.dialect" > ${hibernate.dialect} </prop> &                Lt;prop key= "Hibernate.show_sql" > ${hibernate.show_sql} </prop> <prop key= "Hibernate.jdbc.fetch_size" > ${hibernate.jdbc.fetch_size} </prop&gt       ;         <prop key= "Hibernate.jdbc.batch_size" > ${hibernate.jdbc.batch_size} </ prop> <prop key= "Hibernate.connection.release_mode" > ${hibernate.connection.rel Ease_mode} </prop> <prop key= "Hibernate.format_sql" > ${hibern Ate.format_sql} </prop> <prop key= "Hibernate.connection.SetBigStringTryClob" >tru E</prop> </props> </property> <!--anotation Annotations Scan entity classes--<prope            Rty name= "annotatedclasses" > <list> <value>com.tgb.entity.User</value> </list> </property> </bean> <!--Configure a transaction manager to associate transactions with Hibernate--<bean id= " TransactionManager "class=" Org.springframework.orm.hibernate4.HibernateTransactionManager "> <property name= "Sessionfactory" ref= "SessIonfactory "/> </bean> <!--configuring transaction scope, using proxies--<bean id=" Transactionproxy "class=" org.spring         Framework.transaction.interceptor.TransactionProxyFactoryBean "abstract=" true "><!--inject transaction manager--<property name= "TransactionManager" > <ref bean= "transa for transaction agent Beans Ctionmanager "/> </property><!--set transaction properties range-<property name= "Transactionattributes" > <props> & Lt;prop key= "add*" >PROPAGATION_REQUIRED,-Exception</prop> <prop key= "Get" >propagation_requ                  ired,-exception</prop> <prop key= "update*" >PROPAGATION_REQUIRED,-myException</prop> <prop key= "del*" >PROPAGATION_REQUIRED</prop> <prop key= "*" >propagation_req uired</prop> </props> </property> </bean><bean id= "Userdao" class= "Com.tgb.dao.UserDaoImpl" > <property name= "sessionfactory" ref= "Sessionfactor Y "></property> </bean> <bean id=" usermanagerbase "class=" Com.tgb.manager.UserManagerImpl "> <property name= "Userdao" ref= "Userdao" ></property> </bean> <!--here is Agent--<bean Name= "Usermanager" parent= "Transactionproxy" > <property name= "target" ref= "Usermanagerbase" ></property > </bean></beans>

Reference Links:

http://www.cnblogs.com/andy6163/p/Andy.html simple comprehension-aspect-oriented programming (AOP)

http://blog.csdn.net/moreevan/article/details/11977115 Pring AOP Implementation principle

Five ways to http://blog.csdn.net/it_man/article/details/5074371 Spring transaction configuration

Http://www.cnblogs.com/rushoooooo/archive/2011/08/28/2155960.html Spring Declarative Transaction Configuration management method

Spring Framework IOC container and AOP parsing

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.