Spring_ Learning Notes __spring

Source: Internet
Author: User
Tags aop class definition set set xml example
1.Spring Framework functions and benefits
The spring framework is primarily responsible for technology integration, such as integrating Struts2, Hibernate, and JDBC Technologies.
The advantage is: can improve the flexibility of program structure, reduce the coupling between components, to facilitate future expansion and maintenance.

2.Spring Frame main function
The a.spring framework provides a core container that can be responsible for managing the DAO, action, and other components in the program
The *b.spring framework provides an API for consolidating Struts2, Hibernate, and JDBC Technologies
The C.spring framework provides an IOC mechanism to reduce the coupling of calls between two components
The d.spring framework provides an AOP mechanism to reduce the coupling between common components and a batch of target components.
The *e.spring framework provides transaction management functionality and requires only a few AOP configurations.

3.Spring Frame Container
The Spring framework container can manage bean components such as DAO, action, and so on. The container has the following features:
A. You can create a bean Component Object
B. You can initialize the Bean Component Object
C. You can destroy a bean Component object
D. Containers with IOC and AOP mechanisms

*1 Spring Container Basic use steps
--Introduction of SPRING-IOC development Package
--Add applicationcontext.xml configuration under SRC
--Define the components of DAO and so on Applicationcontext.xml, define the format
   <bean id= "identifier" class= "package name. Class Name" >
   </bean>

--Instantiating the Spring container object
Beanfactory-->applicationcontext (sub-Class)
New Classpathxmlapplicationcontext (container configuration file);
--Gets the bean instance through the container object. Getbean (identifier).


2 The basic characteristics of the spring container for bean management
*a.bean Object creation
The default support for Singleton and prototype is two, that is, a single case and a number of examples. You can use the Scope property to specify that the default value of the property is singleton.
If you are applying a Web program, you can extend a property value such as Request,session through configuration.
B.bean Object Initialization
You can specify a method name by using the Init-method property. This method is automatically invoked to perform initialization logic in the future when a bean object is created.
C.bean Object Destruction
You can specify a method name by using the Destroy-method property. This method is called automatically before the object is garbage collected to perform resource release work.
This property is valid only for scope= "singleton" single Instance bean objects. When the spring container close () is executed, the container releases the Bean Single Instance object, triggering the method specified by Destroy-method.
D.bean Object creation Time
Scope= "Singleton" is created when the container is instantiated. Scope= "Prototype" is created when Getbean (). Use lazy-init= "true" to defer singleton component creation to the Getbean method call.


IOC mechanism of the *4.spring framework
IOC resolves two bean component invocation problems, reducing the coupling between two bean component objects.
1) IOC concept
Inverse of controller is called control reversal or reverse control.
Control refers to the process of creating, initializing, and destroying objects. When a component is changed, the logic needs to be modified accordingly.
Control reversal is exactly the transfer of control, meaning that the control logic is transferred from the use side to the third frame or container. When the component changes occur again, only the frame or container configuration needs to be modified, and the associated components need not be modified.

2) di concept
Dependency injection Dependency Injection.
The dependency injection technology is a method for spring to realize the IOC control thought.
DI has two kinds of injection methods in spring:
*a.setter Mode Injection
The component object is passed in by relying on the set method.
--adding property variables and set methods on the use side
--In the Use Party <bean> definition section, add
<property name= "Property name"
Ref= "Bean Object ID value to inject" >
</property>
B. Structural approach injection
Relies on the constructor method to pass the component object in.
--Adding a construction method with parameters on the use of one side
--In the Use Party <bean> definition section, add
<constructor-arg index= "parameter index"
           ref= "Bean object ID value to inject" >
  </constructor-arg>

3 various types of injection
Spring's di can inject various types of data, which are common in the following ways:
*a.bean Component Object Injection
Use the ref attribute to specify the Bean object ID to inject.
  <property name= "Property name" ref= "id value" >
  </property>
B. Basic data injection
Inject a string, numeric
   <property name= "Property name" value= "Value" >
   </property>
C.list Set Injection
D.set Set Injection
E.map Set Injection
F.properties Injection
5.AOP Concept
Aspect oriented programming aspect-oriented programming.
OOP is object oriented programming and programming focus object.
AOP aspect-oriented programming, which focuses on aspects, refers to common processing components that need to be invoked by multiple other components. AOP is the foundation of OOP programming.
The main problem with AOP is that common components are associated with other components in a low coupling manner.

AOP programming needs to involve several important concepts:
*1) aspect (Aspect)
Refers to a common processing component that needs to be used in the processing of other target components.
*2) pointcut (Pointcut)
Used to specify which components or methods append aspect component functionality. You can use a pointcut expression to specify an
*3) Notice (Advice)
The time and place to specify the role of the aspect component and the target component.
4) Target component (targets)
The component specified by the Pointcut expression is the target component.
5) connection point (Joinpoint)
A pointcut is a collection of connection points. A connection point refers to the information that the aspect component combines with a target component. This object allows you to obtain information such as the target component type and method.
6) Dynamic agent (Autoproxy)
The spring framework implements the AOP mechanism with dynamic proxy technology.
Spring If you use an AOP configuration, the Bean object returned by the container is a new type generated using dynamic proxy technology, which internally invokes the functionality of the aspect component and the original target component.
The spring framework employs two kinds of dynamic proxy technologies.
A.cglib Technology
Target components that are not implemented for interfaces. Using an inheritance method to generate a subclass
public class action$ $EnhancerByCGLIB $234
   extends original Action component type {
  //Rewrite Execute business method,
  //Invoke aspect and Target component functionality
}

B.JDK Proxy API Technology
Target components that are implemented for interfaces. A type is generated using the method of implementing the original target interface
public class new type 
   implements original Target component interface {
  //Rewrite interface business method,
  //Invoke aspect and Target component functionality
}

Spring Notification type
Notifications can specify the order in which the aspect components and target components are executed, and spring provides the following 5 types of notifications.
1) prior notice (Aop:before)
Perform the aspect processing before performing the target component processing
2) post notification (aop:after-returning)
The target component is executed first, no exception is thrown, and the aspect component is executed. If the target has an exception, the aspect component is not executed
3) Final Notice (aop:after)
Execute the target component first, regardless of the exception, to execute the aspect component.
4) exception notification (aop:after-throwing)
The target component is executed first, and the aspect component is executed if an exception is thrown. No exception thrown does not execute.
5) surround notification (Aop:around)
First, execute the Aspect component predecessors, in the execution of the target component, the final implementation of the aspect component rear part. Equivalent front + back structure.
   try{
     //predecessor notification execution-aspect component
     //Execute Target Component processing
     //Post notification execution-aspect component
   }catch () {
     //exception notification execution-aspect component
   }finally{
     / /final notification execution-aspect component
   }

Pointcut
The pointcut is represented by an expression that specifies the target and its methods.
*1) method Limits
You can specify which methods enable aspect component functionality.
Execution (modifier? return type method name (argument list) throws exception?)

Example 1: A method that matches the find start of all bean objects in a container
Execution (* find* (..))
Example 2: Method to find the Costdao component in a matching container
Execution (*
org.tarena.dao.costdao.find* (..))
Example 3: All methods that match all the classes in a DAO package in a container
Execution (* org.tarena.dao.*.* (..))
Example 4: Match all methods in the container for all classes in the DAO package and its child packages
Execution (* Org.tarena.dao. *.*(..))


*2) Type Qualification
Specifies which types of components all methods enable aspect functionality.
Within (package name. Type)
Example 1: All methods for matching Costdao components in a container
Within (Org.tarena.dao.CostDAO)
Example 2: All methods that match all the classes under the action package in the container
Within (org.tarena.action.*)
Example 3: All methods for matching all classes in the action package and its child packages in a container
Within (org.tarena.action. *)

*3) Bean name Qualification
You can qualify by the ID attribute to specify which IDs of Bean objects enable aspect functionality.
Bean (id attribute value)

Example 1: All methods that match a Id=jdbccostdao bean object in a container
Bean (Jdbccostdao)
Example 2: All methods for matching a Bean object with DAO end all IDs in the container
Bean (*dao)

4) Parameter Qualification
You can specify a method parameter list to qualify the target component and method.
Args (parameter list)

Example: A method that matches all beans in a container with only one parameter and the type of the parameter is of the list type
Args (java.util.List)

Note: The above qualifying expressions can be applied in combination, using &&,| | operator connections.

6.Spring Annotation Configuration method
The annotation configuration is a configuration method that can be used from JDK5.0 to support Spring2.5 and above versions.
Note Configuration advantages are simple and convenient. Can replace a large number of XML definitions in Applicationcontext.xml.
Annotations are actually special tags placed before a class, before a method, and before a member variable.
1 Spring Component Scan
All components under the package path can be scanned, and the component class definition is included in the spring container before it is found with the following note marks. Equivalent to the <bean> definition in XML collocation
--@Component (other component applications)
--@Controller (Action component application)
--@Service (Service business component application)
--@Repository (DAO component application)
A. Component scanning techniques are used as follows:
--Open Component scan application in Applicationcontext.xml
<context:component-scan
Base-package= "Scan package path"/>
--Use the note mark before a component such as action or DAO
--Gets the bean object through the container. Getbean () method. The default is to use the first letter lowercase of the class name as the ID value. If you need a custom ID, you can use @repository ("id value")

B. Other <bean> attribute annotation marks:
@Scope ("prototype or singleton") is equivalent to the Scope property
@PreDestroy equivalent to Destroy-method property
@PostConstruct equivalent to Init-method property

2) Annotation of the IOC injection
Defines a @resource or @autowired annotation mark before a member variable or setter method. The default can be injected according to type matching.
If more than one bean object matches the injection, you need to specify the ID value of the injection. Use the following format:
--@Resource (name= "id value to inject")
--@Autowired
@Qualifier ("id value to inject")

3) AOP Annotation Configuration
The annotation configuration uses the following methods:
--Open the AOP annotation configuration in Applicationcontext.xml.
<aop:aspectj-autoproxy/>
--Use the following annotations in the aspect component
@Component//Scan components to spring container
@Aspect//define the component as an aspect component
--Define an empty method in the aspect component and use the @pointcut tag to define the ENTER expression
@Pointcut ("pointcut expression")
public void MyPoint () {}
--in the common method of the aspect component, use the notification annotation mark to cut in.
@Before Forward Notification
@AfterReturning Post Notification
@After Final Notice
@AfterThrowing Exception Notification

@Around Surround Notification

7.Spring with Struts2 consolidation
  1) introduces Struts-spring-plugin.jar development package
        ( You can access the spring container, use the <action> configuration's class attribute value to find the Bean object in the Spring container)
  2) to define the action in the spring container with the ID value and <action> The class attribute values are consistent
  3) define Contextloaderlisener in Web.xml
      (for instantiating the Spring container object at server startup)
  4 using <context-param> to specify the spring container configuration file location in Web.xml

2.strut2-spring-plugin.jar Consolidation Package
  In the STRUTS2 framework, there is a objectfactory component that is responsible for the creation of component objects such as action in the Struts2. A strutsspringobjectfactory component is also available in the
Strut2-spring-plugin.jar package, and the struts.objectfactory of the Struts framework is set to STRUTSSPRINGOBJECTFA Ctory. So when struts receives the request again, it takes advantage of strutsspringobjectfactory to get the action object, and in Strutsspringobjectfactory, provides a way to get the action object, The main logic of the method is as follows:

try{
  //Get web.xml Lisener created Spring container object
  applicationcontext ac = ...;
  Call Ac.getbean () to get the Bean object for the spring container. Use the class attribute to find
 the object action = Ac.getbean (class attribute value)
  //To give the returned action object to the Struts framework processing request
}catch (Exception ex) {
  //When the corresponding bean is not found in the container using the class attribute, execute the following process.
  //Use reflection mechanism to generate a Action object
Class class = Class.forName ("Org.tarena.action.HelloAction1");
Object action = Class.newinstance ();
  Access the spring container to inject the action into the container with the same ID name as the Action object property name.
  //Return action to the Struts framework processing request
}


8.Spring Transaction Management
The Spring Framework provides transaction management capabilities that can be in the following two ways:
*1) declarative transaction management (based on AOP configuration control)
A. Based on XML configuration
A applicationcontext.xml example of a specific configuration reference netctoss-ssh.
Tip: If the action plunges into a transaction as the target object, you need to add the proxy-target-class= "true" attribute to the <aop:config> element. The reason is to inform the spring framework of using cglib technology to generate an action class with transaction management capabilities.

*b. Based on annotation configuration
--Open the transaction annotation configuration in Applicationcontext.xml.

  <bean id= "Txmanager" class= "..." > <property name= "sessionfactory" ref= "...        " >
    </ property>
  </bean>
 <tx:annotation-driven transaction-manager= "Txmanager"/><span style= " Font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); > </span>
--use @transactional in the target component class, which can be defined before the class or before the method

2) programmatic transaction management (based on Java programming control)
Use Transactiontemplate to encapsulate multiple DAO operations as a full transaction control.


2.Spring MVC Framework Application
1 The Spring MVC Framework main components
A.dispatcherservlet
Main controller, equivalent to struts filter
B.controller
Business controller, equivalent to struts action
C.handlermapping
The mapping processor is responsible for maintaining the correspondence between the request and the controller.
D.viewresolver
The view parser, which is responsible for finding the view component based on the view information.
E.modelandview
Model and view component, which is responsible for storing the model data needed for the view identification and response interface

2 Spring MVC Process
A. The client sends a request, and the request first arrives at the Dispatcherservlet host controller.
B. The main controller invokes the Handlermapping component, looking for the corresponding Controller component processing based on the request and controller mapping information.
C. Perform the business processing method of the Controller component Convention, and if database operations are required, you can invoke the DAO component in the business method. When the business method completes, a Modelandview object is returned.
D. The main controller calls viewresolver resolves the Modelandview object and locates the view JSP component based on the view identity information.
E. Generate a response interface for JSP parsing and return it to the browser.



3 Spring MVC Basic Application
Example 1:
Hello.do-->hellocontroller
-->/web-inf/jsp/hello.jsp

Example implementation steps are as follows:
A. Introduction of the spring IOC and WEBMVC development kits
B. Introducing the spring configuration file under src applicationcontext.xml
C. Configure the master controller Dispatcherservlet in Web.xml to specify the spring configuration file location and name.
D. write Hellocontroller components, and pay attention to implementing controller interfaces
E. Defining Hellocontroller components, handlermapping components, viewresolver components in the spring configuration file
F. Add a hello.jsp page under web-inf/jsp




















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.