In-depth introduction to Spring, simple introduction to spring

Source: Internet
Author: User

In-depth introduction to Spring, simple introduction to spring

Preface:A large number of code examples are provided in the notes. It should be noted that most of the code examples are displayed in the form of images, and all the images are from the code I typed, please correct me ~

Part 1: environment construction and IOC container

I. Setup and configuration of Spring environment in Eclipse

1. Click Help --> Install New SoftWare --> Add --> Archive.

2, import the spring-tool-suite-3.6.4.RELEASE-e4.4.2-win32-x86_64.zip compressed package to select the items with Spring IDE, installation can be

3. Import the required jar package

> The log jar package on which spring depends is apache-commons \Commons-logging-1.1.1.jar

> Spring own jar package spring-framework-4.0.0.RELEASE \ libs directory under the 4 jar package, see the following:

> Or import (here log4j stands for log for java)

Note: log standards: spring-framework-3.0.2.RELEASE-dependencies \ org. apache. log4j \ com.springsource.org. apache. log4j \ 1.2.15

Log implementation: spring-framework-3.0.2.RELEASE-dependencies \ org. apache. commons \ com.springsource.org. apache. commons. logging \ 1.1.1

Supplement: copy the log4j. properties file to the class path (src ).

Ii. Spring IOC (Inverse of Control inversion): reverses the right of object creation to the Spring framework.

1Helloworld of IOC

1) create an interface UserService and define an abstract method public void sayHello ();

2) create an interface implementation class UserServiceImpl to implement the abstract method of the interface

public void sayHello(){  System.out.println("Hello Spring...");}

3) create a configuration file for Spring bean management:ApplicationContext. xml

Test:

Note: Spring is callingClassPathXmlApplicationContext ()When the applicationContext. xml file is loaded, the corresponding bean instance is created!

2The core configuration file applicationContext. xml of IOC

Bean node:

Id attribute: indicates a unique Bean. The id attribute value must be unique. It must start with a letter and can contain letters, numbers, hyphens, underscores, sentences, and colons. id: special characters are not allowed.

Class Attribute: Full Bean class name

Scope attribute: Valid value of Bean:

> * Singleton: single-instance, default value

> * Prototype: for multiple instances, when Spring integrates Struts2, the Action class is handed over to Spring for management and must be configured as prototype.

> Requese: In a WEB project, Spring creates a Bean object and stores the object in the request domain, consistent with the request cycle.

> Session: In a WEB project, Spring creates a Bean object and stores the object in the session domain, consistent with the session cycle.

> GolbalSession: In a WEB project, the application is in the Porlet environment. If there is no Porlet environment, globalSession is equivalent to session.

Init-method attribute: The method executed during Bean initialization.

Destroy-method attribute: method executed when Bean is destroyed

Iii. Spring Dependency Injection (DI: Dependency Injection): When the Spring framework is responsible for creating Bean objects, it dynamically injects Dependency objects into Bean components.

1. Two dependency injection methods:

Note: Perform dependency injection,Whether it is a value type attribute or a reference type attribute, you must create the corresponding attribute in the corresponding bean and provide the setter method (except for annotation injection)

Test: Regular call

2. constructor injection Properties

1) inject reference type attributes

> Construct a Car

> Configure bean

2) inject reference type attributes

> Create a Person class and add a Car reference.

> Configure bean

3. Inject attributes of array and set types

1) inject the attributes of the array and List set, and useList Node(In the property node)

2) inject attributes of the Map set type and useMap NodeAndEntry NodeConfiguration

Note: The configuration of the Set is similar to that of the Map Set.Set NodeConfiguration

3) inject Properties set type attributes usingProps and prop nodesConfiguration

Note: You need to define the attributes of these set types in the class, and then add the setter method.

Add: Spring configuration file development:

> Include another configuration file in one configuration file (usually used ):

<Import resource = "applicationContext2.xml"> </import>

> Load multiple configuration files when creating a factory (rarely used ):

 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml","applicationContext2.xml");

Iv. Integrate Web with Spring

1. Import the required jar package: E: \ jar package open source framework-under the new \ spring-framework-4.2.4.RELEASE \ libs directorySpring-web-4.2.4.RELEASE.jar

2. InListener Configuration in web. xmlThis listener is created when the container loads the ServletContextListener. Therefore, instances in the IOC container are also created only once when the Web container is loaded.

3. Modify the previous factory code to useWebApplicationContextMethod

 

5. IOC Annotation

1. Build the environment:

(1) introduce the required aop jar package, spring-framework-4.2.4.RELEASE \ libs \Spring-aop-4.2.4.RELEASE.jar

② Introduce context constraints: spring-framework-4.2.4.RELEASE \ docs \ spring-framework-reference \ html \Xsd-configuration.htmlCopy

Enable annotation Scanning

2. Annotations:

1) Here we use@ ComponentComponents

The test is the same as the conventional factory.

Supplement: @ Component has three derivative Annotations:

@ Controller: Used on the WEB layer

@ Service: Used at the Business Layer

@ Repository: Used in the persistent layer

Note: These three annotations are used to clarify the purpose of the tag class. The functions are consistent with those of @ Component.

2) Use@ ValueAnnotation injection basic data type attributes

 

3) inject reference type attributes

Method 1: Use@ AutowiredAnd@ Qualifier

 

Method 2: Use@ Resource provided by JavaAnnotation

4) use annotations to set Bean Scope

Set above the class@ Scope (value = "prototype ")Optional values: singleton and prototype

 

5) Configure Bean lifecycle (add method ).

@ PostConstruct is equivalent to init-method

@ PreDestroy is equivalent to destroy-method.

 

Vi. Integrate JUnit unit testing with Spring to facilitate testing

1. Import the requiredSpring-test-4.2.4.RELEASE.jaR jar package spring-framework-4.2.4.RELEASE \ libs \ spring-test-4.2.4.RELEASE.jar

2. Add annotations for unit test classes:

@ RunWith (SpringJUnit4ClassRunner. class)

@ ContextConfiguration ("classpath: applicationContext. xml ")

3. Use:

Part 2: Spring AOP

I. AOP Overview

1. AOP: Aspect Oriented ProgrammingAspect-Oriented Programming

2. Adopt AOPHorizontal Extraction MechanismInstead of the repetitive code of the traditional horizontal inheritance system, it can mainly achieve: performance monitoring,Transaction Management, Security check, cache, and other functions

3. Advantage: You can enhance the program without modifying the source code.

Ii. Underlying Implementation of AOP

1. JDK-based Dynamic Proxy:Class that implements the interfaceGenerate the proxy instance Code (the code can be understood ):

> Define the UserDAO (Interface) and UserDaoImpl (Implementation class) classes, and create the save () and update () methods.

> Define the proxy class:

2.CglibDynamic Proxy:Class generation proxy without interface implementationThe underlying bytecode enhancement technology is used to generate the subclass object of the current class. The instance code (you can understand the code ):

> Define the BookDaoImpl class and create the save () and update () methods.

> Create a proxy class

 

Iii. terms related to AOP Development

1. Joinpoint: the so-called connection point refers to the points intercepted. In spring, these points referMethodBecause spring only supports connection points of the method type.

2. PointcutWhich joinpoints are intercepted?.

3. Advice (notification/enhancement): refersWhat to do after intercepting JoinpointNotifications are classified into pre-notifications, post-notifications, exception notifications, and final notifications,Surround notification(Functions to be completed)

4. introduction (Introduction): (yes) Introduction is a special notification. without modifying the class code, Introduction can dynamically add some methods or fields for the class at runtime.

5. Target (Target object): the Target object of the proxy, for example, BookDaoImpl UserDaoImpl

6. Weaving: refers to the process of applying enhancement to the target object to create a new proxy object. That is:Process of generating a class proxy object

7. Proxy: After a class is woven into the enhancement by AOP, a result Proxy class is generated. That is:Generated proxy object

8. Aspect (Aspect): A combination of the entry point and notification (Introduction. We need to write and configure it by ourselves (the notification needs to be written by ourselves, and the entry point needs to be configured)Aspect: Entry Point + notification

Iv. Specific development of AspectJ AOP in XML Mode

1. Environment Configuration

1) import the required jar package

*SpringBasic jar packages for framework development

* Traditional spring AOP development packages

Spring-aop-4.2.4.RELEASE.jar

Com.springsource.org. aopalliance-1.0.0.jar

(Spring-framework-3.0.2.RELEASE-dependencies \ org. aopalliance \ com.springsource.org. aopalliance \ 1.0.0)

* AspectJ development kit:

Com.springsource.org. aspectj. weaver-1.6.8.RELEASE.jar

(Spring-framework-3.0.2.RELEASE-dependencies \ org. aspectj \ com.springsource.org. aspectj. weaver \ 1.6.8.RELEASE)

Spring-aspects-4.2.4.RELEASE.jar

2) Configure constraints to applicationContext. xml

2. Specific use:

Prepare: Define the interface: CustomerDao, create the save () and update () Methods

Define implementation class: mermerdaoimpl

Define the Test method:

 

1) create a partition class:

2) Configure aop in the applicationContext. xml file

Supplement: Expression of the AOP entry point:

Supplement: notification types of AOP

>Pre-notification (aop: before): Run the command before the method of the target class is executed.

>Final notification (aop: after): Run the command after the method of the target class is executed. If the program encounters an exception, the notification will also be executed.

>Post-execution (aop: after-returning): Run the command after the method of the target class is normal.

> Exception throw notification (aop: after-throwing): notification after the target class throws an exception

>Surround notification (aop: around): notifications before and after implementation of the target Class Method

NOTE: Special attentionSurround notification:

V. AOP technology of Spring framework ------ annotation Method

1. Prepare the environment

1) Introduce relevant jar packages. For details, see Module 4.

2) the constraints on the applicationContext. xml file of spring-3 have been comprehensively introduced.

3) ① define interface: CustomerDao, create save () and update () method ② define implementation class: CustomerDaoImpl ③ create Test Method

4) write the face-cutting class MyAspectAnno and configure the face-cutting class in the applicationContext. xml file.

 

5) get started with AOP Annotations:

> Configure in applicationContext. xmlEnable Automatic proxy for AOP annotations

> Set annotation in face-cutting class

2. Notification types and common entry points of AOP annotations

1) Notification Type:

* @ Before: pre-notification

* @ AfterReturing: post notification

* @ Around: surround notification (the method of the default target object is not executed)

* @ After: final notification

* @ AfterThrowing: indicates that an exception is thrown.

2) Demo:

Supplement: configure a common entry point

Vi. Spring JDBC template Technology

1. Environment configuration-import the required jar package and configuration file

You also need:

2. Use the Spring-JDBC template classJdbcTemplate

> Do not use IOC container management. manually create a JdbcTemplate object by using the database connection pool built in the Spring framework.DriverManagerDataSource

 

> Use IOC container to manage data sources

① Configure the database connection pool (built-in Spring) and JdbcTemplate in the applicationContext. xml file

② Use:

3. Use the Spring framework to manage open-source database connection pools

1) ManagementDBCPDatabase Connection Pool

> Import the required two jar packages and find them in the Spring dependency package.

(1) spring-framework-3.0.2.RELEASE-dependencies \ org. apache. commons \ com.springsource.org. apache. commons. dbcp \ 1.2.2.osgi \Com.springsource.org. apache. commons. dbcp-1.2.2.osgi.jar

(2) spring-framework-3.0.2.RELEASE-dependencies \ org. apache. commons \ com.springsource.org. apache. commons. pool \ 1.5.3 \Com.springsource.org. apache. commons. pool-1.5.3.jar

 

> Configure the DBCP database connection pool in applicationContext. xml

2) ManagementC3P0Database Connection Pool

> Import the required jar package and find it in the Spring dependency package.

Spring-framework-3.0.2.RELEASE-dependencies \ com. mchange. c3p0 \ com.springsource.com. mchange. v2.c3p0 \ 0.9.1.2 \Com.springsource.com. mchange. v2.c3p0-0.9.1.2.jar

> Configure the C3P0 database connection pool in applicationContext. xml

4. Use of the JDBC template class --- add, delete, modify, and query

1) add, delete, and modify operations

 

2) query the usage of a recordQueryForObject ()Method

 

To customize the implementation class, first define a JavaBean: Account, and then:

 

3) query the List of a group of records and useQuery ()Method

 

VII. Spring transaction management

1. APIs related to Spring transaction management

1)PlatformTransactionManagerInterface -----Platform Transaction Manager(The class that truly manages transactions. This interface has a specific implementation class (DataSourceTransactionManagerAndHibernateTransactionManager), Depending on the persistence layer framework, you need to select different implementation classes)

2)TransactionDefinitionInterface-transaction definition information, such as transaction isolation level, Propagation Behavior, timeout information, read-only or not

Supplement: Transaction Propagation Behavior constant (commonly used ):

* Ensure that the same transaction is in progress

PROPAGATION_REQUIREDSupports the current transaction. If the transaction does not exist, a new one (Default, usually used)

* Ensure that the transaction is not in the same transaction

PROPAGATION_REQUIRES_NEWIf a transaction exists, the current transaction is suspended and a new transaction is created. 

* PROPAGATION_NESTED: if the current transaction exists, the nested transaction is executed.

3)TransactionStatusInterface ------ Transaction Status

2. Case study: setting up the transfer environment

1) import the required jar package

IOC: 6 packages AOP: 4 integrated JUnit: 1 c3p0: 1 jdbc: 2 Mysql drivers: 1 import configuration file (2)

2) Write AccountService, AccountDao interface, and its implementation class AccountServiceImpl, AccountDaoImpl see the spring-3-tx Project

3)JdbcDaoSupportClass: IfInheritanceYou can use the getJdbcTemplate () method to obtain the JdbcTemplate object:

① Because JdbcDaoSupport has the JdbcTemplate attribute, you can directly configure the JdbcTemplate class in the applicationContext. xml file and inject the JdbcTemplate class as a property into other classes using this class.

② According to the source code analysis of JdbcDaoSupport, you can directly configure and inject the database connection pool without configuring and injecting template classes in the applicationContext. xml file.

Example:

3. Manage transactions

1) Spring's programmatic Transaction Management (understand it)

① Configure the platform Transaction Manager

 

② Configure the TransactionTemplate template class

 

③ Inject the transaction template class at the business layer, that is, TransactionTemplate.

 

④ Use TransactionTemplate to manage transactions

 

2)Spring declarative Transaction Management Based on AOP

① XML configuration file method (the business layer method does not need to be modified)

> Configure platform Transaction Manager

> Configure the notification first. Note: tx: method can set database attributes for the method, such as isolation level and Propagation Behavior. The name attribute values of tx: method can contain *, for example, pay * indicates the method starting with pay.

 

> Configure the AOP aspect.

 

② Use annotations to manage transactions

> Configure platform Transaction Manager

> Enable transaction Annotation

 

> Add a transaction on the corresponding class (indicating that all methods in this class Add a transaction) or method (only this method adds a transaction)@ TransactionlAnnotation

 

8. Integrate three SSH frameworks with Spring

Summary:

1. Integrate Spring with Struts2

1) Method 1: Action is created and managed by Struts2 and depends onStruts2-spring-plugin-2.3.24.jarThis jar package(Not recommended)

① Configure Action in the struts. xml file

② Call the class at the business layer in the Action. As long as the class at the business layer is configured in the Spring configuration file, create an instance at the business layer in the Action and provide the setter method, you can directly call the methods at the business layer.

2) Method 2: submit the Action to Spring for creation and management (recommended)

① Configure Action in the Spring configuration file,You must configure

② Reconfigure the Action configuration in the Struts. xml configuration file. If the Action is managed by Spring, the class attribute of the action node is the id attribute value of the bean node where the Action is configured in the Spring configuration file.

③ In the Spring configuration fileInject reference attributes of the business layer into Action

④ Use: Define the reference attribute of the relevant business layer in the Action class, define the setter method, and use it.

2. Integrate Hibernate with Spring

1) Method 1: With the hibernate. cfg. xml configuration file (Not recommended)

① Classes at the persistent layer need to be inheritedHibernateDaoSupport, Which hasHibernateTemplateReference properties. The source code shows that this class can also get the hibernateTemplate object by configuring SessionFactory. Because the persistence layer class inherits the HibernateDaoSupport, that is, it obtains its hibernateTemplate reference attribute and SessionFactory reference attribute, so SessionFactory can be directly injected into the Spring configuration file for the persistence class.

 

② Generate Hibernate according to hibernate steps. cfg. xml and class name. hbm. xml file and configure it accordingly. Note: hibernate. cfg. the binding to the current thread cannot be configured in xml; otherwise, an error is returned!

③ Configure in the Spring configuration fileLocalSessionFactoryBean, UsedLoad the hibernate. cfg. xml file and create the SessionFactory object

 

④ In SpringConfigure the platform Transaction Manager in the configuration fileAndEnable transaction Annotation, And in the correspondingAdd @ Transactionl annotation to the class or method of the Business Layer

 

2) Method 2: does not contain the hibernate. cfg. xml configuration file (recommended)

Thinking: without the hibernate. cfg. xml configuration file, you can configure the content in the hibernate. cfg. xml configuration file in the Spring configuration file. Therefore, based on Method 1:

① In the Spring configuration fileConfigure the c3p0 Data Source:

 

② InIn LocalSessionFactoryBeanConfigure the database connection pool, dialect, optional values (whether to print SQL statements, whether to format SQL statements, and data table generation policies), and introduce the ing configuration file

 

3. Hibernate template class ---HibernateDAOSupportUse

1) HibernateDAOSupport'sGetHibernateTemplate () The method is similar to that of Hibernate sessions. You can add, delete, and modify databases.

 

2) query a record, HQL query all records, QBC query all records, and paging Query

 

4. Solve the Problem of SSH framework integration delayed Loading

1) Use the HIbernateTemplate. load () method. The default value is delayed loading.

2) exception: java. lang. classCastException: qi. spring. ssh1.domain. customer _ $ _ export sist_0 cannot be cast to multicast sist. util. proxy. the Proxy is caused by a package conflict. Delete the earlier version.

 

3)Lazy loading error: Org. hibernate.LazyInitializationException: Cocould not initialize proxy-no Session is caused by the Session closed during Delayed loading.

Solution:

Solution 1: add the lazy = "false" attribute to the class node in Customer. hbm. xml to disable delayed loading. It is not recommended. This Scheme Reduces Program performance.

Solution 2:Spring solves the problem of delayed loading.,Configure a filter in the web. xml fileNote: This filter must be configured before the core filter of struts2,This method is recommended.!!

 

Related Article

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.