I. Spring concept
1. is an open source lightweight framework
2.spring Core main two parts
(1) AOP: aspect-oriented programming, extension function is not to modify code implementation
(2) IOC: Inversion of Control: the creation of objects in a way that does not pass new, but rather to the spring configuration to create objects
3.spring is a one-stop frame
In Java EE's three-tier architecture, each layer offers a different solution
Web layer: SPRINGMVC
Service:spring's IOC
DAO Layer: Spring's JdbcTemplate
4.ioc
1 give the creation of the object to spring management
2 IOC operation two parts
A.IOC configuration file Mode
The way of annotation of B.IOC
3 Bottom principle (engage in low coupling)
A. Bottom-up use technology
A.xml configuration file
B.DOM4J Resolve XML
C. Factory design pattern
D. Reflection
4 configuration file steps
A:spring Core configuration file name and location is not fixed, the proposal is placed under SRC, the official recommendation name is Applicationcontext.xml
B: Introducing Schema constraints
<beans xmlns= "Http://www.springframework.org/schema/beans"
xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "
xsi:schemalocation="
http://www.springframework.org/schema/beans http:// Www.springframework.org/schema/beans/spring-beans.xsd ">
<!--Configure entity classes-->
</beans>
C: Configuring Objects
<!--parameterless construction configuration-->
<bean id= "user" class= "Cn.zsl.bean.User" ></bean>
5.Bean Management--configuration file mode
(1) Bean instantiation mode three kinds
A: Create using a class's parameterless construct (emphasis)
B: Using static factory creation: Creating a static Method return object
C: Create using instance factory: Instead of static method, create object of class to return
(2) Bean label Common Properties
ID: Name, id attribute value name arbitrarily named, cannot contain special symbol. Get configuration object based on ID
Class: Create a full path to the class where the object is located
Name: Like the feature and ID attribute, the id attribute cannot contain special symbols, but then the attribute value can contain special symbols, which are basically not necessary.
Scope: Contains the following values
Singleton: Default value, single case, only one object
Prototype: Multiple cases
Request: Create an object put the object in the request
Session: Creating objects putting objects into session
Globalsession: Creating objects putting objects into globalsession
(3) Attribute injection: When creating an object, set the value to the property inside the class
Three kinds of attribute injection methods in A:java
A. Injecting using a parameter-structured method
B. Injecting using the Set method
C. Using interface injection
B: Configuration file injection class attribute value, only support above A, B two methods
A. Using a parameter-structured method injection, using the Constructor-arg tag, the Name property represents the member variable name, and value represents the values to be passed in
<bean id= "user" class= "cn.zsl.bean.User" >
<constructor-arg name= "name" value= "John" ></ Constructor-arg>
</bean>
B. Using the Set method injection, using the property label, the name attribute represents the member variable name, and value represents the values to be passed in
<bean id= "user" class= "cn.zsl.bean.User" >
<property name= "name" value= "John" ></property>
</bean>
C: Injecting object type attributes (emphasis)
If a class contains objects of Class B, the method implemented by IOC
A. Use B as the type attribute in a
B. Generate a set method of type B
C. Injecting object properties into a configuration file, adding a property tag to a Property,name property represents a member variable name, and ref represents the ID value in the Class B Configuration Bean label
<bean id= "B" class= "cn.zsl.bean.b" ></bean>
<bean id= "a" class= "Cn.zsl.bean.a" >
< Property name= "Name" ref= "B" ></property>
</bean>
D: Injecting complex data
A. Array type: Using the value tag under the list label under the property label to assign values to a group
B.list collection: Assigning values to the list collection using the value tag under the list label under the property label
C.map Collection: Assign a value to a map collection using the entry tag under the map label under the property label, key is the value
D.properties: Properties are assigned using the prop tag under the props label under the property label, and key is the key in the entity
<bean id= "user" class= "Cn.zsl.bean.User" > <!--array property assignment--> <property name= "Array" >
<list> <value> John </value> <value> Dick </value>
<value> Harry </value> </list> </property> <!--Assigning a value to the list property-->
<property name= "List" > <list> <value> Mobile </value> <value> pc </value> <value> Flatbed </value> </list> </prope Rty> <!--assign value to map property--> <property name= "map" > <map> <e
Ntry key= "AA" value= "Tom" ></entry> <entry key= "BB" value= "Jerry" ></entry> <entry key= "cc" value= "Friends" ></entry> </map> </property> < Property Name= "PropertieS "> <props> <prop key=" username ">root</prop> <prop key = "Password" >123</prop> </props> </property> </bean>
Differences between E:IOC and DI
IOC: Control reversal, giving the creation of objects to spring management
DI: Dependency Injection, injecting values into properties in a class
Relationship: Dependency Injection does not exist alone and needs to be done on an IOC basis.
6.Spring consolidates Web Project principles
(1) Load Spring core profile
New object, functionality achievable, inefficient
(2) Implementation idea: To load the configuration file and create the object process in the Complete the
(3) Implementation principle at server Startup:
A:servletcontext object
B: Listener
(4) specific process
A. When the server starts, the system creates a Servletco for each project ntext Object
B. Use a listener when a ServletContext object is created to monitor when a ServletContext object is created
C. When the ServletContext is created, the project loads the spring configuration file, Create a configuration object in the configuration file
D. Place the created object inside the ServletContext domain object (setattribute () method)
E. Objects are obtained in the ServletContext field (getattrib Ute () method)
7.Bean Management-Annotation Method
(1) Annotation: Special tags inside code, use annotations to complete functionality
Annotation style: @ Note Name (property name = attribute value)
Annotation You can use the above classes, methods, and Properties
(2) Step:
A. Import jar packages, including a basic spring package and a note pack
B. Create classes, properties, and methods
C. Create a configuration file, introduce a constraint, turn on the annotation scan
<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= Www.w3.org/2001/XMLSchema-instance "xmlns:context=" Http://www.springframework.org/schema/context "xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context.xsd "> <!--open annotations scan into packages scan classes, methods, attributes on whether there are annotations if you scan annotations in multiple classes, you can let Base-package=" cn . ZSL ", if it is a class under different packages, you can even let base-package=" cn "--> <context:component-scan base-package=" Cn.zsl.bean "></conte Xt:component-scan> <!--only scans the annotations on the attributes above--> <context:annotation-config></context:annotation-config&
Gt </beans>
D. Note Create object 4 annotations
@Component (vlaue= "user")//And < bean id= "user" class= "> Effect, User represents object name
@Con Troller:web Layer
@Service: Business layer
@Repository: Persistence layer
4 effects are the same and use the same.
E: Create Single-instance objects
@scope (value= "singleton")//singleton default values, single instance, prototype multiple instances other usages See profile mode
(3) Property note Into
A. @Autowired automatically inject
B. @Resourse (name= "user"): Name indicates assignment, and if injected object type, the value value of the annotation creation object is the same or the ID of the object created by the profile method is the same
Note: Using the annotation method, the Class A set method of Class B object properties is not required, and the label is automatically injected into the
(4) Injection Object type attribute
If Class A contains object B, the annotation method is used to implement
A: Create Class A and type B
B: Annotation way to create objects of Class A and B
C: Define B-type properties in Class A, inject the object's properties with the annotation label
7. Profile and note blending
Create objects using the configuration file method. Injection properties are annotated with
Two. AOP
1.AOP: Aspect-oriented programming, taking a horizontal extraction mechanism, replacing the traditional vertical inheritance system with repetitive code.
2.AOP principle:
3.AOP Operating Terminology:
4.ASPECTJ: AOP operations within Spring, using ASPECTJ to implement
(1) AspectJ is not part of spring and is used with spring for AOP operations
(2) Spring2.0 new support for ASPECTJ
(3) There are two ways of using ASPECTJ to implement AOP
A. xml-based configuration based on AspectJ
B. Annotations based on ASPECTJ
5.ASPECTJ Use Preparation
(1) configuration file Introduction constraint
<beans xmlns= "Http://www.springframework.org/schema/beans"
xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "
xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "xsi:schemalocation="
http:// Www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http:// WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop.xsd "> <!--Bean Definitions here-->
</beans>
(2) Using an expression to configure Pointcuts
A. Point of entry: a practical enhancement approach
B. Commonly used expression execution (< access modifier >?< return type >< method name > (< parameter >) < exception >)
A. Execution (* Cn.itcast.aop.Book.add (..)): Represents the Add () method of the book class under the CN.ITCAST.AOP package
B. Execution (* cn.itcast.aop.book.* (..)) : Represents all methods of the book class under the CN.ITCAST.AOP package
C. Execution (* * *. * (..)): means all methods
D. Methods to match all save starts execution (* save* (..)) : Represents all methods that start with Save
6. configuration file mode using ASPECTJ AOP operations
(1) Adding enhanced classes and methods
If you are adding a around surround enhancement method, you need to add a proceedingjoinpoint type parameter to the method that invokes the enhanced method through the proceed () method of the parameter, which proceedingjoinpoint.proceed ( ) means that the method is enhanced
public void Aroundadd (Proceedingjoinpoint proceedingjoinpoint) throws Throwable {
//method before
System.out.println ( "Before wrapping");
Call Enhanced Method
Proceedingjoinpoint.proceed ();
System.out.println after the method
("wrapping");
(2) Configure the object to add a configuration object to the class to be used in the configuration file
<!--Add a MyBook class to the Add () method of the book Class--> <!--1 Configuration object--> <bean id= "book" class= "Cn.zsl.bean.Book" &G t;</bean> <bean id= "MyBook" class= "Cn.zsl.bean.MyBook" ></bean> <!--2 Configure AOP Operations--> ;aop:config> <!--2.1 configuration pointcut--> <aop:pointcut expression= "Execution (* cn.zsl.bean.book.* (..))" Id= "Pointcut1"/> <!--2.2 Configuration slice: Use enhancements to the method--> <aop:aspect ref= "MyBook" > <!--
Configure the enhanced type Aop:before: predecessor-enhanced Aop:after: Post-enhanced Aop:around: surround-enhanced ...
Method: In the enhanced class, which is used as the enhancement method Pointcut-ref: The Pointcut (method) to be enhanced to be the same as defined above--> <aop:before method= "Beforeadd" pointcut-ref= "pointcut1"/> <aop:after method= "Afteradd" pointcut-ref= "Pointcut1"/> <aop:around method= "Aroundadd" pointcut-ref= "Pointcut1"/> T;/aop:aspect>;/aop:config>
7.LOG4J: View logs using log4j
How to use:
(1) Import the log4j jar package
(2) Copy log4j configuration file, copy to SRC below
Set Log Level
(1) Info: see basic information
(2) Debug: See more details
8.Spring Consolidated Web Project
Spring configuration files are loaded each time the action is accessed
(1) Solution:
A. Creating an object-loading profile at server startup
B. Low-level use of listeners, ServletContext objects
(2) In spring we do not need to write our own code implementation, will help us encapsulate
A. Encapsulates a listener and only needs to configure the listener
B. Before configuring the Listener do things: Import the Spring Consolidation Web Project Jar Pack (Spring-web-4.2.4.release.jar)
C. Specify load Spring configuration file location
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value> Classpath:bean1.xml</param-value>
</context-param>
9. Annotation mode using ASPECTJ AOP operations
(1) Creating enhanced classes and methods
(2) Configuration classes and enhanced class objects
(3) configuration file Open AOP operation
<!--open AOP operations-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
(4) using annotations to complete AOP operations above the enhanced class
A. Add a @aspect label to a class
B. Add @before, @After, @Around labels to the method, and the child label value is a common expression execution (< access modifier >?< return type >< method name > (< parameter >) < exception >), as follows:
@Before (value= "Execution (* cn.zsl.bean.book.* (..))")
10.Spring of JdbcTemplate operation
(1) Spring frame one-stop frame
For Java EE three layers, each layer has a resolution technology
On the DAO layer, use the JdbcTemplate
(2) Spring's encapsulation of different persistence layer technologies
Dbctemplate use is very similar to dbutils use, all databases for CRUD operations
(3) Use method
A. Importing Jar Packs
B. Creating objects, setting Database information
C. Creating a JdbcTemplate object, setting the data source
D. Call the methods in the JdbcTemplate object to implement the operation
additions and deletions are called the update () method to implement
Configuration database Information
drivermanagerdatasource dataSource = new Drivermanagerdatasource ();
Datasource.setdriverclassname ("Com.mysql.jdbc.Driver");
Datasource.seturl ("Jdbc:mysql:///springjdbctemplatetest");
Datasource.setusername ("root");
Datasource.setpassword ("root");
Creates a JdbcTemplate object, sets the data source
jdbctemplate JdbcTemplate = new JdbcTemplate (dataSource);
Call the Update method inside the JdbcTemplate object to implement the
String sql = INSERT INTO user value (?,?);
int rows = jdbctemplate.update (sql, "Zhangsan", "num");
SYSTEM.OUT.PRINTLN (rows);
(4) Query data operation
Configuring the database is the same as creating the JdbcTemplate object step, calling the method different
A. Find returns a value
Lookup returns a value, the queryForObject () method, the first parameter represents the SQL statement, and the second parameter represents the class file
String sql = "SELECT COUNT (*) from user"
of the type that returns the value. int count = jdbctemplate.queryforobject (sql, integer.class);
System.out.println (count);
B. Find returns an object, at which point you need to create an object of the RowMapper interface to encapsulate the found data
Finds the returned object, invokes queryForObject (), the first parameter represents the SQL statement, the second parameter represents the RowMapper interface object, represents the user object that gets to a row of data, and the third parameter is the variable parameter
String sql = " SELECT * FROM user where username =? ";
User user = Jdbctemplate.queryforobject (sql, New Myrowmapper (), "Zhangsan");
SYSTEM.OUT.PRINTLN (user);
Class Myrowmapper implements rowmapper<user>{
@Override public
User Maprow (ResultSet rs, int num) throws SQLException {
//1 the data from the result set to
String username = rs.getstring ("username");
String Password = rs.getstring ("password");
2 package The resulting data into the object
user user = new user ();
User.setusername (username);
User.setpassword (password);
return user;
}
C. Query return list collection
Finds the returned object, calls the query () method, the first parameter represents the SQL statement, and the second parameter represents the RowMapper interface object
String sql = "SELECT * from user";
list<user> list= jdbctemplate.query (SQL, New Myrowmapper ());
SYSTEM.OUT.PRINTLN (list);
11. Configure C3P0 connection pooling and DAO use JdbcTemplate
(1) Configure C3P0 Connection pool
(2) DAO use JdbcTemplate
1 Create service and DAO, configure service and DAO objects, inject DAO objects in service
2 Create the JdbcTemplate object and inject the template object into the DAO
3) inject DataSource into the JdbcTemplate object
12. Transaction Management
(1) Things: The most basic unit of database operation
(2) The characteristics of things: atomicity, consistency, isolation, durability
(3) Do not consider the problems arising from segregation:
Dirty reads: One transaction reads the uncommitted update data for another transaction.
Non-repeatable reads: One transaction reads the same row of data two times, but the data read two times is different.
Phantom reads: A transaction executes two queries, but a second query has some data rows more than the first query.
Missing update: When you undo a transaction, overwrite the updated data that was submitted by the other transaction.
(4) Solution: Set Isolation Level
(5) Spring Transaction Management API