Spring framework IOC container and AOP parsing, spring framework iocaop

Source: Internet
Author: User

Spring framework IOC container and AOP parsing, spring framework iocaop
Main analysis points:

I. Introduction to the Spring open-source framework

Ii. IOC containers and DI in Spring (Dependency injection)

Iii. configuration of Aspect-oriented programming (AOP) and transaction management in Spring

 

I. Introduction to the Spring open-source framework

  Spring is an open-source framework. Spring was a lightweight Java development framework that emerged in 2003, it is derived from part of the concepts and prototype stated by Rod Johnson in his book "Expert One-On-One J2EE Development and Design. It is created to solve the complexity of enterprise application development. Spring uses the basic JavaBean to complete the previous tasks that may only be completed by EJB. However, Spring is not only used for server-side development. From the perspective of simplicity, testability, and loose coupling, any Java application can benefit from Spring.In short, Spring is a lightweight container framework for IoC and AOP.

 The basic framework of spring mainly includes six modules: DAO, ORM, AOP, JEE, WEB, and CORE.

Spring DAO: Spring provides JDBC operation support: JdbcTemplate template tool class.

Spring ORM: Spring can be integrated with the ORM framework. For example, Spring integrates the Hibernate framework. Spring also provides the HibernateDaoSupport tool class, which simplifies Hibernate operations.

Spring WEB: Spring provides support for Struts and Springmvc and supports WEB development. Spring also provides MVC-based solutions.

Spring AOP: Spring provides Aspect-oriented programming, which can provide transaction management for a certain layer, for example, adding transaction control at the Service layer.

Spring JEE: Support for J2EE development specifications, such as EJB.

Spring Core: Allows you to create and process dependency objects in an IOC container.

 

Ii. IOC containers and DI in Spring (Dependency injection)

  IOC container: A container with dependency injection is a container that can create objects. The IOC container is responsible for instantiating, locating, configuring objects in the application, and establishing dependencies between these objects. A new instance is usually controlled by a programmer, while a "control inversion" means that a new instance is handed over to a Spring container instead of a programmer .. In Spring, BeanFactory is the actual representative of the IOC container.

  DI(Dependency injection): After the container creates an object, it processes the object dependency.

Injection Method of dependency injection spring:

      • Set Injection Method
      • Static factory Injection Method
      • Constructor Injection Method
      • Annotation-Based Method

1. set injection method:

Control Layer Code:

private OrderServiceImp orderService;    public void setOrderService(OrderServiceImp orderService) {       this.orderService = orderService;}

Spring configuration XML file: the configuration declaration OrderAction class has the attribute orderService. When the program runs, it will call the setOrderService method to inject the instantiated orderService object.

<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. annotation-based method (recommended for ease of use and less configuration)

Control Layer Code:

@Autowired   //@Resourceprivate OrderServiceImp orderService;

Service Layer Code:

 
@Service("orderService")public class OrderServiceImp implements IOrderService {    @Autowired    private JavaOrderMDaoImp javaOrderMDao;    @Autowired    private JavaOrderDDaoImp 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:

(1) The name specified in the persistence layer DAO layer annotation Repository. The declaration name must be consistent in the Service layer.

(2) The Service layer annotation Service specifies the name. The names declared in the control layer must be consistent.

(3) annotation injection dependency annotation:

 
@ Component adds the object to the ioc container. The object reference name is the class name, and the first letter is lowercase @ Component ("name, add ioc container @ Repository is mainly used to identify the object to be added to the container as a persistent layer component (class) @ Service is mainly used to identify the object to be added to the container as a component of the business logic layer @ Controller is mainly used to identify the object to be added to the container as a control layer component @ Resource injection attribute (DI ), the @ Autowired injection attribute (DI) will be injected from the container to the @ Resource modified object, and the @ Autowired modified object will be injected from the container.
 

(4) annotations can simplify configuration and improve development efficiency, but they are not conducive to later maintenance.

 Note: The difference between @ Autowired and @ Resource

 

Iii. configuration of Aspect-oriented programming (AOP) and transaction management in Spring

AOP is vertical programming. For example, both business 1 and business 2 require a common operation. Instead of adding the same code to each business, it is better to write the code again, let the two businesses use this code together. In daily business such as order management, commodity management, capital management, and inventory managementLog records,Transaction Control,Permission control, performance statistics, exception handling, and transaction processing. AOP extracts all the common codes and places them in a specific place for centralized management. Then, the containers dynamically weave these common codes at specific runtime.

 

AOP Name:

Aspect (Aspect): It is actually the implementation of common functions. Such as log aspect, permission aspect, and transaction aspect. In practice, a common Java class is usually used to store common functions. The reason why the Java class can be recognized as a plane by the AOP container is specified in the configuration.

Advice): Is the specific implementation of the aspect. Taking the target method as a reference point, according to different places, it can be divided into pre-notification (Before), post-notification (AfterReturning), exception notification (AfterThrowing), and final notification (After) there are 5 types of Surround notifications. In practice, it is usually a method in the face-cutting class. The specific type of notification is also specified in the configuration.

Join point (Joinpoint): The place where the program can insert a cut surface during running. For example, method call, exception throw, or field modification, but Spring only supports method-level connection points.

Pointcut): Defines the connection points to which notifications should be redirected. Different notifications usually need to be switched to different connection points. This exact match is defined by the regular expression of the starting point.

Target object): Objects to be cut-in, that is, objects to be notified. Only the core business logic code is left in these objects, and all the common functional code is waiting for the AOP container to cut in.

Proxy): Dynamically created object after the notification is applied to the target object. The proxy object function is equivalent to the core business logic function of the target object and a common function. Proxy objects are transparent to users and are the product of the program running.

Weaving): Apply the aspect to the target object to create a new proxy object. This process can occur during the compilation, class loading, and runtime. Of course, different occurrences have different preconditions. For example, a special compiler that supports the implementation of AOP is required when it occurs during the compilation period. When it occurs during the class loading period, a special class loader that supports the implementation of AOP is required; the reflection and dynamic proxy mechanisms of the Java language can be used for dynamic implementation only at runtime.

 

Spring uses AOP to configure transaction management. It consists of three parts:DataSource,TransactionManagerAndProxy mechanismRegardless of the configuration method, the agent mechanism is usually changed. DataSource and TransactionManager only change according to the data access method. For example, when hibernate is used for data access, DataSource is actually SessionFactory, and the implementation of TransactionManager is HibernateTransactionManager.

 

 

Five spring transaction Configuration Methods: Each Bean has a proxy, all beans share a Proxy Base class, use the interceptor,Interceptor configured using the tx tag, Full Annotation

1,Interceptor configured using the tx tag

 
<! -- 4. Configure the hibernate Attributes --> <! -- Introduce db. properties file --> <bean class = "org. springframework. beans. factory. config. propertyplaceholderpolicer "> <property name =" location "value =" classpath: db. properties "> </property> </bean> <! -- Configure the data source. The connection pool uses c3p0. For more information, see the hibernate Official Document "basic configuration" --> <bean id = "dataSource" class = "com. mchange. v2.c3p0. comboPooledDataSource "destroy-method =" close "dependency-check =" none "> <property name =" driverClass "> <value >$ {datasource. driverClassName} </value> </property> <property name = "jdbcUrl"> <value >$ {datasource. url} </value> </property> <property name = "user"> <value >$ {datasource. username} </value> </property> <Property name = "password"> <value >$ {datasource. password} </value> </property> <property name = "acquireIncrement"> <! -- The number of connections that c3p0 obtains at the same time when connections in the connection pool are exhausted. Default: 3 --> <value >$ {c3p0. acquireIncrement} </value> </property> <property name = "initialPoolSize"> <! -- The number of connections obtained during initialization. The value must be between minPoolSize and maxPoolSize. Default: 3 --> <value >$ {c3p0. initialPoolSize} </value> </property> <property name = "minPoolSize"> <! -- The minimum number of connections retained in the connection pool. --> <Value >$ {c3p0. minPoolSize} </value> </property> <property name = "maxPoolSize"> <! -- The maximum number of connections retained in the connection pool. Default: 15 --> <value >$ {c3p0. maxPoolSize} </value> </property> <property name = "maxIdleTime"> <! -- Maximum idle time. connections are dropped if they are not used within 60 seconds. If it is 0, it will never be discarded. Default: 0 --> <value >$ {c3p0. maxIdleTime} </value> </property> <property name = "idleConnectionTestPeriod"> <! -- Check all idle connections in the connection pool every 60 seconds. Default: 0 --> <value >$ {c3p0. idleConnectionTestPeriod} </value> </property> <property name = "maxStatements"> <! -- JDBC standard parameter, used to control the number of PreparedStatements loaded in the data source. However, the pre-cached statements belong to a single connection rather than the entire connection pool. Therefore, you need to consider many factors when setting this parameter. If both maxStatements and maxStatementsPerConnection are 0, the cache is disabled. Default: 0 --> <value >$ {c3p0. maxStatements} </value> </property> <property name = "numHelperThreads"> <! -- C3P0 is asynchronous, and slow JDBC operations are completed by helping the process. These operations can effectively improve the performance. Multiple operations can be executed simultaneously through multiple threads. Default: 3 --> <value >$ {c3p0. numHelperThreads} </value> </property> </bean> <! -- Configure 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. dialect ">$ {hibernate. dialect} </prop> <prop key = "hibernate. show_ SQL ">$ {hibernate. show_ SQL} </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 = "hibernate. connection. release_mode ">$ {hibernate. connectio N. release_mode} </prop> <prop key = "hibernate. format_ SQL ">$ {hibernate. format_ SQL} </prop> <prop key = "hibernate. connection. setBigStringTryClob "> true </prop> </props> </property> <! -- Anotation annotation scan object class --> <property name = "packagesToScan"> <list> <value> com. pec. model </value> </list> </property> </bean><! -- 5. Spring configuration declarative things -->    <! -- Configure transactions --> <bean id = "transactionManager" class = "org. springframework. orm. hibernate3.HibernateTransactionManager "> <property name =" sessionFactory "ref =" sessionFactory "> </property> </bean> <! -- Configure the transaction scope --> <tx: advice id = "txAdvice" transaction-manager = "transactionManager"> <tx: attributes> <tx: method name = "get *" read-only = "false" propagation = "NOT_SUPPORTED"/> <tx: method name = "find *" read-only = "false" propagation = "NOT_SUPPORTED"/> <tx: method name = "save *" propagation = "REQUIRED"/> <tx: method name = "update *" propagation = "REQUIRED"/> <tx: method name = "delete *" propagation = "REQUIRED"/> <tx: m Ethod name = "create *" propagation = "REQUIRED"/> <tx: method name = "anscy *" propagation = "REQUIRED"/> </tx: attributes> </tx: advice> <! -- Define a plane --> <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 several notes:

(1) In the three "*" in pointcut, the first * indicates the return value, the second * indicates the sub-package of the service, the third * indicates the method name, and "(...)" indicates the method parameter.

(2) The configuration point is located at the Service layer. The method name must start with the advice notification point.

(3) According to the prescribed naming method, it is subject to the control of Spring transactions and maintains operation consistency. For example, if 100 pieces of data are inserted into the database and all the first 99 records are normally executed until 100th errors occur, the transaction control will roll back to the initial status before execution.

 

2. Use 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 ht Tp: // www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://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.springframework.org/schema/aop/spring-aop-2.5.xsd "default-autowire =" defa Ult "> <! -- <Bean name = "userManager" class = "com. tgb. manager. userManagerImpl "> </bean> <bean name =" userController "class =" com. tgb. web. userController "> <property name =" userManager "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-SC An base-package = "com. tgb. web"/> <! -- Introduce init. properties> <bean id = "placeholderConfig" class = "org. springframework. beans. factory. config. propertyPlaceholderConfigurer "> <property name =" locations "> <list> <value> classpath: config/spring/jdbc. properties </value> </list> </property> </bean> <! -- Configure the data source. The connection pool uses c3p0. For more information, see the hibernate Official Document "basic configuration" --> <bean id = "dataSource" 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> <property name =" password "value =" $ {datasource. password} "> </property> </Bean> <! -- Configure SessionFactory --> <bean id = "sessionFactory" class = "org. springframework. orm. hibernate4.LocalSessionFactoryBean "> <property name =" dataSource "ref =" dataSource "/> <property name =" hibernateProperties "> <props> <prop key =" hibernate. dialect ">$ {hibernate. dialect} </prop> <prop key = "hibernate. show_ SQL ">$ {hibernate. show_ SQL} </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 = "hibernate. connection. release_mode ">$ {hibernate. connection. release_mode} </prop> <prop key = "hibernate. format_ SQL ">$ {hibernate. format_ SQL} </prop> <prop key = "hibernate. connection. setBigStringTryClob "> true </prop> </props> </property> <! -- Anotation annotation scan object class --> <property name = "annotatedClasses"> <list> <value> com. tgb. entity. user </value> </list> </property> </bean> <! -- Configure a Transaction Manager to associate the transaction with Hibernate --> <bean id = "transactionManager" class = "org. springframework. orm. hibernate4.HibernateTransactionManager "> <property name =" sessionFactory "ref =" sessionFactory "/> </bean> <! -- Configure the transaction scope and use proxy --> <bean id = "transactionProxy" class = "org. springframework. transaction. interceptor. TransactionProxyFactoryBean" abstract = "true"><! -- Inject Transaction Manager into transaction proxy bean --> <property name = "transactionManager"> <ref bean = "transactionManager"/> </property><! -- Set the transaction property range --> <property name = "transactionAttributes"> <props> <prop key = "add *"> PROPAGATION_REQUIRED, -Exception </prop> <prop key = "get"> PROPAGATION_REQUIRED,-Exception </prop> <prop key = "update *"> PROPAGATION_REQUIRED, -myException </prop> <prop key = "del *"> PROPAGATION_REQUIRED </prop> <prop key = "*"> PROPAGATION_REQUIRED </prop> </props> </property> </bean><Bean id = "userDao" class = "com. tgb. dao. userDaoImpl "> <property name =" sessionFactory "ref =" sessionFactory "> </property> </bean> <bean id =" userManagerBase "class =" com. tgb. manager. userManagerImpl "> <property name =" userDao "ref =" userDao "> </property> </bean> <! -- Here is the proxy --> <bean name = "userManager" parent = "transactionProxy"> <property name = "target" ref = "userManagerBase"> </property> </bean></Beans>
 

 

Reference link:

A simple understanding of http://www.cnblogs.com/andy6163/p/Andy.html-AOP)

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

Five methods for configuring http://blog.csdn.net/it_man/article/details/5074371 spring transactions

Spring declarative transaction configuration management method for http://www.cnblogs.com/rushoooooo/archive/2011/08/28/2155960.html

 

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.