I Spring framework overview
1. Spring is an open source lightweight Java EE framework.
Lightweight: small size, independent use of jars, no need to rely on other jar packages,
Open source: free, source code can be provided
Framework: solve the complexity of development and simplify enterprise development.
2. Two core parts of spring: IOC and Aop
IOC: inversion of control, leaving the process of creating objects to spring for management.
Aop: aspect oriented, adding or enhancing functions without modifying the source code.
3. Features of spring framework:
1) , facilitate decoupling and simplify development: the relationship between objects depends on spring.
2) , Aop programming support: do not change the source code and enhance functions
3) , convenient for testing;
4) , it is convenient to integrate various excellent frameworks.
5) To facilitate food management and reduce the difficulty of using API
6) , java source code, classic learning examples.
4. Introduction case:
1) , Download spring 5:
Spring website: spring.com io
Direct download address: https://repo.spring.io/artifa...
Also download a log jar package. Spring 5 depends on this jar package, the Commons login jar
Download link: commons-logging-1.1.1 Jar download, Maven and Gradle introduced code, pom file and class - era Java in the package (nowjava. Com)
I personally download 5.2.6
2) , after downloading, join a common java project and import the jar into the project
3) , using spring
(1) , create a common class and create a common method in the class
public class User { public void add(){ System.out.println("add......."); } }
(2) , create a spring configuration file, and configure the created objects in the configuration file
a. The Spring configuration file uses an xml file for configuration
<?xml version="1.0" encoding="UTF-8" ?> <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"> <!--to configure User objects creating--> <bean id = "user" class = "com.yuge.User"></bean> </beans>
b. Create Test class Test
public class Tset { @Test public void testAdd(){ //1. Read in the context configuration file ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml"); //2. Get the configuration object User user = context.getBean("user", User.class); System.out.println(user); user.add(); } }
c. Test results, successfully create the object and call the method
2, IOC container
1.IOC underlying principle
1) , what is IOC:
Inversion of control, the creation of objects and the interaction between objects are handed over to spring for management.
2) , purpose of using IOC
To reduce coupling
3) IOC introduction case
2. IOC underlying principle
1) , xml parsing, factory schema, reflection
2) Graphic IOC underlying principle
Traditional way:
Factory mode:
IOC mode:
3.IOC interface (BeanFactory)
IOC is based on the container, and the bottom layer of IOC container is the object factory
1) , BeanFactory interface:
The most basic implementation of IOC container is the internal interface of spring, which is not recommended for developers.
2) , ApplicationContext interface:
It is a sub interface of BeanFactory and provides more powerful functions than BeanFactory. It is generally used by developers
3) , the difference between the two interfaces
When we use the Spring framework, we usually use it in conjunction with the web page. When we use BeanFactory to create objects, we will not create objects. When loading configuration files, we use tomcat when the server is started. All the time-consuming and non space consuming things such as system loading files are completed when tomcat is started to provide a better user experience, so we use the ApplicationContext interface
4) , implementation class of applicationContext
3.IOC operation Bean Management (based on xml)
1) , what is bean Management:
A. bean management consists of two steps: Spring object creation and spring attribute injection
2) , implementation method of bean Management:
a. Implementation based on xml configuration file
1. Create objects based on XML
id attribute: give the class classpath an alias
Class attribute: creates the full path of the object class
Creating default objects in XML mode uses null parameter constructor by default
2. Attribute injection based on XML
(1) , DI: dependency injection, that is, injection attributes.
Difference between DI and IOC: DI is an implementation of IOC.
Method 1: use set injection
(a) , create the object of the class, and create the set method
(b) , configure object creation and attribute injection in the configuration file
Method 2: injection using parametric construction method
Method 3: p namespace injection:
Step 1:
Step 2:
3. Inject null values and special characters
1, Inject null
2, Inject special symbols
4. Inject bean s
1) , inject external bean s
Introducing external beans and calling Dao layer with service is the process of introducing external beans.
2) Injecting internal bean s and cascading assignments
Cascade assignment method 1: get method of dept is not required.
Cascade assignment method 2: the second method needs to create the get method of dept.
5. Inject set attributes
0), create Stu class, User class
package com.yuge; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; public class Stu { //Array type private String course[]; //List type private List<String> name; //Map type private Map<String,String> map; //Set type private Set<String> set; //Store multiple objects in List type private List<User> userList; public void setUserList(List<User> userList) { this.userList = userList; } public void setCourse(String[] course) { this.course = course; } public void setName(List<String> name) { this.name = name; } public void setMap(Map<String, String> map) { this.map = map; } public void setSet(Set<String> set) { this.set = set; } public void show(){ System.out.println(Arrays.toString(course)); System.out.println(name); System.out.println(map); System.out.println(set); System.out.println(userList); } }
package com.yuge; public class User { private String name; public void setName(String name) { this.name = name; } public void add(){ System.out.println("add......."); } @Override public String toString() { return "User{" + "name='" + name + '\'' + '}'; } }
1). XML injection array type attribute
2) , XML injection List collection attribute
3) , XML injection Map collection properties
4) , XML injection Map attribute
5) , inject object attributes into the collection:
<?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:m="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--to configure Stu objects creating--> <bean id="stu" class="com.yuge.Stu"> <!--Inject array properties--> <property name="course"> <array> <value>javaSe</value> <value>Mysql</value> </array> </property> <!--injection List object--> <property name="name"> <list> <value>Wuba</value> <value>Baba</value> </list> </property> <!--injection Map object--> <property name="map"> <map> <entry key="JAVASE" value="javase"></entry> <entry key="SPRING" value="Spring"></entry> </map> </property> <!--injection Set object--> <property name="set"> <set> <value>Zhang San</value> <value>the other woman</value> </set> </property> <!--stay list Inject object properties into--> <property name="userList"> <list> <ref bean="user1"></ref> <bean id="user1=2" class="com.yuge.User"> <property name="name" value="Li Hua"></property> </bean> </list> </property> </bean> <bean id="user1" class="com.yuge.User"> <property name="name" value="Li Ye"></property> </bean> </beans>
6) , create a test class
package com.yuge.test; import com.yuge.Stu; import com.yuge.User; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.applet.AppletContext; public class Tset { @Test public void testAdd(){ //Load profile ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean2.xml"); //create object Stu stu = (Stu) applicationContext.getBean("stu"); stu.show(); } }
7) , output results
8). Extract all bean s as public collections
Step 1: introduce a new namespace:
Step 2: use the util tag to complete the upward extraction of list set injection
Create a new Book class to test the upward extraction and injection list
package com.yuge; import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput; import java.util.List; public class Book { private List<String> bookList; public void setBookList(List<String> bookList) { this.bookList = bookList; } public void test(){ System.out.println(bookList); } }
Configure the method of extracting and injecting list from XML file:
<?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:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <util:list id="list"> <value>java From entry to earth</value> <value>python From entry to prison</value> </util:list> <bean id="book" class="com.yuge.Book"> <property name="bookList" ref="list"></property> </bean> </beans>
Operation result: extraction succeeded
What it looked like before extraction:
After extraction:
You can also extract more objects.
6. Two kinds of bean s in Spring
1) Ordinary bean: the type defined in XML will be returned
2) , factory bean: defines a type in XML and can return other types
Step 1: create a class as a factory bean and implement the interface of FactoryBean
Step 2: implement the method in the interface and define the returned bean type in the implemented method
package com.yuge.factoryBean; import com.yuge.Stu; import org.springframework.beans.factory.FactoryBean; public class Mybean implements FactoryBean<Stu> { @Override public Stu getObject() throws Exception { Stu stu = new Stu(); return stu; } @Override public Class<?> getObjectType() { return null; } @Override public boolean isSingleton() { return false; } }
Step 3: configure the XML file
<bean id="myBean" class="com.yuge.factoryBean.Mybean"> </bean> Test: @Test public void testMyBean(){ ApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml"); Stu stu = context.getBean("myBean",Stu.class); System.out.println(stu); }
result:
7. Scope of bean:
When configuring bean s in XML, single instance or multiple instances:
8. Automatic assembly of XML
Automatic assembly: Spring automatically fills in the matching attribute values according to the specified assembly rules (attribute name or attribute type).
Demonstrate automatic assembly:
1. Assemble according to the name
2. Assemble according to attribute type
9. Introduce external attribute management
4.IOC operation Bean (annotation based)
1. Annotations provided by spring for creating objects
Step 1: introduce dependency:
Step 2: start component scanning
Step 3: create a class and add annotations on the class.
1, @ Component, you can use the change annotation to create objects
2, @ service, generally used in business logic layer or service layer
3, @ Controller, generally used for Web layer
4, @ Repository, generally used for Dao layer
The above qualification annotations have the same functions, but each annotation is used in different layers for developers to distinguish.
2. Open the detailed configuration of component scanning configuration
3. Use annotation to access attributes
1) , @ Autowired: automatically inject according to the attribute type
Step 1: create objects in each class using annotations.
Step 2: define object attributes. Add comments on attributes. The set method is not required.
2) , @ Qualifier: inject according to the attribute name
3) , @ Resource: can be injected according to attribute name and attribute type
The above three types are injection objects, not ordinary types*
4) , @ Value: inject common type
4. Full annotation development
1) , create a configuration class to replace the XML configuration file
2) , write test classes
3, Aop
Face the aspect, and strengthen the function without modifying the source code.
1. What is AOP
Isolate each logic of the business, so as to reduce the logical coupling between the businesses, improve the reusability of the code and improve the development efficiency.
2. Underlying principle of AOP
1. Dynamic agent is used at the bottom of AOP
1. Dynamic agent with interface and dynamic agent with JDK
Create the proxy object of the implementation class of the interface and enhance the method of the class
2. Dynamic agent without interface, using CGLIB dynamic agent
Create the proxy object of the subclass and enhance the method of the class
2. Dynamic agent using JDK
Using proxy class to realize dynamic proxy
Code implementation:
1. Create interface:
package com.JDK Dynamic agent; public interface UserDao { public int add(int a,int b); public String update(String id); }
2. Create an implementation class
package com.JDK Dynamic agent; public class UserDaoImpl implements UserDao{ @Override public int add(int a, int b) { return a+b; } @Override public String update(String id) { return id; } }
3. Use the proxy class to create the dynamic proxy object of the interface
package com.JDK Dynamic agent; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.security.PublicKey; import java.security.UnresolvedPermission; import java.util.Arrays; public class JDKProxy { public static void main(String[] args) { Class[] interfaces = {UserDao.class}; UserDao dao = (UserDao)Proxy.newProxyInstance(UserDaoProxy.class.getClassLoader(), interfaces, new UserDaoProxy(new UserDaoImpl())); int res = dao.add(1, 2); System.out.println(res); } } class UserDaoProxy implements InvocationHandler{ //You need to transfer the object of the class to be enhanced to the proxy class, and instantiate it through the construction method of the proxy class //Create a proxy object of UserDaoImpl through UserDaoProxy private Object obj; public UserDaoProxy(Object obj){ this.obj = obj; } @Override /** *The addition logic is written in this method * @ proxy:Proxy object * @ method:Methods that need to be enhanced * @ args: Parameters required for methods to enhance functionality */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //Before method System.out.println("Method before executing..."+method.getName()+"Parameters passed:"+ Arrays.toString(args)); //Enhanced method execution Object res = method.invoke(obj, args); //Execute after method System.out.println("Execute after method..."+obj); return res; } }
3. Relevant terms in AOP
1. Connection point: those methods that can be enhanced are called connection points.
2. Entry point: the way the world is really enhanced is called entry point.
3. Notification (enhancement): the logical part that is actually enhanced is called notification or enhancement.
There are many types of notifications:
4. Aspect: the action of applying the notification to the pointcut is called aspect
##4. AOP operation preparation
1. Spring frameworks generally implement AOP operations based on AspectJ
AspectJ: it is not a part of the spring framework. It is independent of AOP framework. Spring and AOP framework are generally used together for AOP operation.
2. Realize AOP operation based on AspectJ
(1) , AOP operation based on XML configuration file
(2) , based on annotation (use)
3. Introduce AOP related dependencies in the process of the project.
4. Pointcut expression
(1) , the function of pointcut expression: know which method in which class to enhance.
(2) , syntax structure:
execution: ([Permission modifier][Return type][Class full path][Method name](Parameter list)
Example 1: execution(* (return value can be omitted) com yuge. UserDaoImpl. add(..));
Strengthen com yuge. Userdaoimpl's add() method, the parameters passed in are Indicates that the permission modifier is * and the return value type is omitted.
Example 2: execution (return value can be omitted) com yuge. UserDaoImpl. (..)); Enforce all methods in the class.
Example 3: execution (return value can be omitted) com yuge..* (..)); Enforce all methods of all classes in the package
5. AOP operation (AspectJ annotation)
1. Create a class, define a method in the class, and use annotations to enhance the method in the class.
package com.AOP Annotation method; public class User { public void add(){ System.out.println("add..................."); } }
2. Create an enhancement class and write enhancement logic
package com.AOP Annotation method; //Enhancement class public class UserProxy { //Before advice public void before(){ System.out.println("before............."); } }
3. Configure notifications
(0). Introducing namespace
(1) , in the spring configuration file, turn on annotation scanning
<!--Enable annotation scanning--> <context:component-scan base-package="com.AOP Annotation method"></context:component-scan>
(2) , use annotations to create User objects and UserProxy objects.
(3) , add the @ Aspect annotation on the enhanced class
(4) , turn on the generation proxy object in the spring configuration file.
<!-- Enable AspectJ to generate proxy objects -- >
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
(5) , configure different types of notifications
a,On the enhanced class method, add the notification type. Configuring with pointcut expressions package com.AOP Annotation method; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; //Enhancement class @Component @Aspect //Generate proxy object public class UserProxy { //Pre notification. If the before annotation is added, the before method will be executed before the add() method. @Before("execution(* com.AOP Annotation method.User.add(..))") public void before(){ System.out.println("before............."); } //Execute after method execution @After("execution(* com.AOP Annotation method.User.add(..))") public void after(){ System.out.println("after............."); } //Execute when there is an exception in the method @AfterThrowing("execution(* com.AOP Annotation method.User.add(..))") public void afterThrowing(){ System.out.println("afterThrowing............."); } //Execute after method returns @AfterReturning("execution(* com.AOP Annotation method.User.add(..))") public void afterReturning(){ System.out.println("afterReturning............."); } //Add a wrap method, which is executed before and after the method is executed @Around("execution(* com.AOP Annotation method.User.add(..))") public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { System.out.println("Before surround............."); //Enhanced method execution proceedingJoinPoint.proceed(); System.out.println("After surround.............."); } }
package com.AOP Annotation method; import org.springframework.stereotype.Component; @Component public class User { public void add(){ System.out.println("add..................."); } } package com.AOP Annotation method; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { @org.junit.Test public void testAdd(){ //Load the context configuration and read the xml configuration file ApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml"); //Get object User user = (User)context.getBean("user"); user.add(); } } <?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" 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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd "> <!--Enable annotation scanning--> <context:component-scan base-package="com.AOP Annotation method"></context:component-scan> <!--open AspectJ Generate proxy object--> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <bean id="user" class="com.AOP Annotation method.User"></bean> </beans>
Operation results:
b. Summary:
after It will be executed whether there are exceptions or not, afterReturning It will not be executed when there are exceptions.
OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP OP op OP OP OP OP OP OP OP OP OP OP OP OP OP op
1. Extract the same entry point
//Extract the same pointcut @Pointcut(value = "execution(* com.AOP Annotation method.User.add(..))") public void pointCut(){ } //Pre notification. If the before annotation is added, the before method will be executed before the add() method. @Before("pointCut()") public void before(){ System.out.println("before............."); } //Execute after method execution @After("execution(* com.AOP Annotation method.User.add(..))") public void after(){ System.out.println("after............."); }
2. When multiple enhancement classes enhance the same method, set the priority of enhancement classes
Set priority on multiple enhanced classes. Use the annotation @ Order (integer value). The smaller the integer value, the higher the priority
//Enhancement class @Component @Aspect //Generate proxy object @Order(3) public class UserProxy { //Extract the same pointcut @Pointcut(value = "execution(* com.AOP Annotation method.User.add(..))") public void pointCut(){ }
@Component @Aspect @Order(0) public class UserProxy2 { @Before("execution(* com.AOP Annotation method.User.add(..))") public void before(){ System.out.println("UserProxy2 The enhanced class executes....."); } }
7. AOP operation (XML configuration file)
The premise is to create objects of enhanced classes and enhanced classes in xml
8. Full annotation development
4, JdbcTemplate
1. The concept of JdbcTempalte
Spring encapsulates JDBC, and the use of JdbcTemplate can facilitate the operation of the database.
preparation:
Import dependency:
Configure XML to create class injection properties
2. Use the JdbcTemplate template to add, delete, modify and query the database
<context:component-scan base-package="com"/> <bean id = "dataSource" class="com.druid.DruidDataSource" destroy-method="close"> <property name="url" value="jdbc:mysql://localhost:3306/jdbc_db"/> <property name="username" value="root"/> <property name="password" value="3.141592654"/> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <!--injection dataSource object--> <property name="dataSource" ref="dataSource"></property> </bean>
public interface BookDao { void add(Book book); }
@Repository public class BookDaoImpl implements BookDao { //Inject the JdbcTemplate object @Autowired private JdbcTemplate jdbcTemplate; @Override public void add(Book book) { String sql = "insert into book values(?,?,?)"; int update = jdbcTemplate.update(sql, book.getId(), book.getName(), book.getPrice()); System.out.println(update); } }
@Service public class BookService { //Inject BookDao attribute @Autowired private BookDao bookDao; public void insert(Book book){ bookDao.add(book); } }
package com.druid; public class DruidDataSource { String url; String password; String username; String driverClassName; public void setUrl(String url) { this.url = url; } public void setPassword(String password) { this.password = password; } public void setUsername(String username) { this.username = username; } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } private void close() { } }
package com.test; import com.bean.Book; import com.service.BookService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestJdbcTemplate { @Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml"); BookService bookService = context.getBean("bookService", BookService.class); Book book = new Book(); book.setId(1); book.setName("One Yang finger"); book.setPrice(250); bookService.insert(book); } }
The query returns a value
Query returns an object
The query returns a collection
##3. Batch operation of database using JdbcTemplate template
5, Transaction operation
1. Concept of transaction:
Review: a transaction is a set of basic data operation units that either complete all operations or do not complete all operations.
Typical transaction scenario: bank transfer
Four characteristics of transactions (ACID): atomicity, consistency, isolation and persistence
2. Establishment of business environment
3. Introduction to spring transaction management
1. Add transactions to the Service layer (business logic layer) of the three-tier architecture of Java EE
2. In Spring transaction operation:
1) , there are two ways: Programming (adding code to the method) and declarative (XML based or annotation based)
2) , declarative transaction management: the underlying uses AOP
3) , Spring transaction management related API s
4. Propagation behavior between multiple transactions:
5. Isolation level of ioslation transaction:
Transaction isolation: the operations of multiple transactions will not affect each other
If isolation is not considered, it will lead to dirty reading, unreal reading and non repeatable reading
Resolution isolation level:
Configure isolation level: