0. Summary
1.mybatis
- For the initial packaging of JDBC, MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures and advanced mapping. MyBatis avoids almost all JDBC code and manually setting parameters and getting result sets. MyBatis can use simple XML or annotations for configuration and native maps to Map interfaces and Java POJOs(Plain Old Java Objects) into records in the database.
2. Connection pool c3p0,druid
Responsible for database connection, creating connection and releasing connection.
Users need to obtain a link from the database every request, and creating a connection to the database usually consumes relatively large resources and takes a long time. Assuming that the website has 100000 visits a day, the database server needs to create 100000 connections, which greatly wastes the resources of the database, and it is very easy to cause the memory overflow and expansion of the database server.
It is mainly used to manage database connection
- C3P0 database connection pool
After using the database connection pool, there is no need to write the code to connect to the database in the actual development of the project. The database connection is obtained directly from the data source. - Druid's advantages over other database connection pools:
3. Transaction processing
Transaction management of database. Ensure the normal operation of the database. Act on the data source.
1.ioc container
- The first step is to specify the bean class and class id through xml configuration. You can also configure some initialization parameters
- id is the main way to get the bean from the page.
- Create factory class -- > create object through reflection (class.newInstance)
1.ioc interface
-
ioc is a container, which is essentially an object factory.
-
spring provides two interfaces implemented by the Ioc container
-
Beanfactory spring is used internally and is generally not available to developers.
-
ApplicationContext: it is provided for developers to use and has richer functions.
Difference: the former creates an object when the bean is called, while the latter automatically generates a bean object when the configuration file is loaded.
-
2.ioc specific operation
1.bean creation
- spring helps us create objects
- Spring helps us inject properties
2.bean management
-
Create objects based on xml,
- id unique identifier
- Full path of class object class
- name and id are similar.
The parameterless constructor and get/set function are executed by default.
java is the same as C + + when running. If there is no constructor, a parameterless constructor is automatically created. If there is a constructor, the parameterless constructor is not injected
-
xml based attribute injection
<bean id="user" class="com.demo.spring5.User"> <property name="name" value="1111"/> </bean>
-
Construction with parameters: constructor ARG
- Name attribute name or index: the first parameter (starting from 0)
<bean id="user1" class="com.demo.spring5.User"> <constructor-arg name="name" value="1111" /> <constructor-arg index="0" value="1"/> </bean>
-
p namespace injection: essentially no set
xmlns:p="http://www.springframework.org/schema/p" <bean id="user2" class="com.demo.spring5.User" p:name="22"></bean>
1. How to inject special values
- Null < null / >
- Injection of special symbols
<property name="name"> <null/> </property> <!--Injection of special symbols--> <bean id="user3" class="com.demo.spring5.User"> <property name="name" > <value><![CDATA[<<Nanjing>>]]></value> </property> </bean>
2. How to inject bean s
Contains internal beans and cascading beans
-
Create service class and Dao class,
-
Implement the internal injection of bean s through ref.
<!--Joint level bean--> <!-- bean Medium injection bean--> <bean id="userDao" class="com.demo.dao.UserDaoImp"/> <bean id="userService" class="com.demo.service.UserService"> <property name="userDao" ref="userDao"/> <!--You can also give it directly userDao The attribute assignment in needs to be set userDao of get method--> <property name="userDao.name"value="name"/> </bean> <!--inside bean,stay property Add inside bean--> <bean id="userService" class="com.demo.service.UserService"> <property name="userDao"> <bean id="userDao" class="com.demo.dao.UserDaoImp"/> </property> </bean>
3. Injection attribute - internal bean and cascade assignment
- One to many relationships: departments and employees
- Entity classes represent one to many relationships
3. Inject collection attributes based on xml
1. Injection array
2. Inject list set and
3. Inject mapper attribute
<bean id="student" class="com.example.bean.Stu"> <property name="courses"> <array> <value>java</value> <value>sql</value> </array> </property> <property name="list"> <list> <value>Zhang San</value> <value>the other woman</value> </list> </property> <property name="map"> <map> <entry key="Java" value="88"></entry> <entry key="C++" value="88"></entry> </map> </property> <property name="set"> <set> <value>Three good students</value> <value>Excellent Communist Youth League member</value> </set> </property> </bean>
4. Inject object array
<!-- Assign a value to a collection of objects--> <property name="coursesList"> <list> <ref bean="course1"/> <ref bean="course2"/> </list> </property>
5. Extract set
The collection can be extracted through the util tool for multiple use
<?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-2.5.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <util:list id="bookList"> <value>Jiuyang Shentong</value> <value>Book of changes</value> </util:list> <bean id="book" class="com.example.bean.Book"> <property name="list" ref="bookList"></property> </bean> </beans>
4. Factory bean
Beans in Spring can be divided into two types: Factory beans and ordinary beans.
There is such a difference
- Ordinary bean: in the configuration file definition, the bean type is the return value type
- Factory bean: configuration type and return type can be different.
1. Single instance and multi instance
Explanation: normally, it is a single instance. There is only one bean object in the factory. No matter where the bean is taken for use, multiple instances will be recreated every time the bean is taken and recycled automatically.
Scope attribute: @ scope
- prototype: multi instance, lazy loading
- singleton: single instance,
- Request: it will be automatically placed in the request after each creation
- Seesion: it will be automatically placed in the seesion field after each creation
2. Custom factory bean
The effect is the same as that of multiple instances
Generally speaking, the instance receiving type of a bean registered in xml can only be the relationship between the preset class and its subclasses or the inherited interface. A factory bean is to register a factory, and the obtained type is the product of a bean.
characteristic:
- Inherit factorybean < course > interface
- Pass in product class for acceptance
public class MyBean implements FactoryBean<Course> { @Override public Course getObject() throws Exception { Course coursec = new Course(); coursec.setName("abc"); return coursec; } @Override public Class<?> getObjectType() { return null; } }
5.bean life cycle
What are the processes from object creation to object destruction??
- Create bean instance (parameterless construction)
- Inject values into bean properties (set method)
- Call the method initialized in the bean (configuration required)
- bean is ready to use (object acquisition)
- Close the container and destroy the bean
<bean id="book" class="com.example.bean.Book" init-method="Init" destroy-method="destory"> <property name="list" ref="bookList"></property> </bean>
In addition, there can be two redundant steps to set the pre and post processors before and after initialization.
Pre and post processor of bean
It refers to adding pre and post processors before and after initialization. BeanPostProcessor
Beans can actually be expanded into seven steps.
- Set up front and rear processors
- Configure front and rear processors
- The post processor can be directly registered as a bean in xml, and this processor is valid for all beans
public class MyBeanPost implements BeanPostProcessor{ @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } } <bean id="myBeanProcess" class="com.example.bean.MyBeanPost"/>
6. Automatic injection
There are two methods for automatic injection: byname and bytye. In particular, it has bean id and class to inject attributes.
<bean id="book" class="xxxx" autowire="byName"/> <bean id="book" class="xxxx" autowire="byType"/>
byName is the id injection of the bean
- Turn on automatic injection
Summary: in fact, automatic assembly can be regarded as secondary bean injection after preliminary bean injection. There is no order when writing configuration. Management belonging to bean
3.bean management
1. Attribute value separation
1. To import the external configuration file context: Property placeholder, you need to add a namespace first
2. ${} takes the value of the attribute,
<xmlns:context="http://www.springframework.org/schema/context" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="classpath:jdbc.properties"/>
4. Notes
To simplify xml configuration
1. Create object
- @Component
- @Service
- @Controller
- @Repositry
The functions are consistent, just for the convenience of development
Steps:
- Introduce dependency
- Turn on component scanning. Multiple components are separated by commas
- Many attributes are arrays. If you use split in xml configuration, use {} plus split in annotation
<context:component-scan base-package="com.example.bean,com.example.bean.Course"/>
Packet scanning writing method
- Multiple packages are separated by commas
- If use default filters is set to false, you can set your own scanning conditions. The scanning conditions here are scanned according to the type of annotation
- Turn off the default filter and turn on the class you define to scan
- Use the default filter to turn off the corresponding scan class
- Excluded content can be scanned by default plus excluded content
<context:component-scan base-package="com.autowire.bean" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
1. Attribute analysis
- value ~~id is not written. The default is the class name
2. Injection attribute
1.bean injection
@Autowired
bean injection, which is automatically injected according to the type.
There is no need to add a set method to help us encapsulate
@Qualifier
Name injection requires the joint use of multiple @ autowires. When there are multiple bean s of the same type, it is very suitable for name injection
@Resource
Used alone, it is in javax
- @Resource
- @Resource(name="userDao1")
Mixed mode injection.
@Service(value="userService") public class UserService { @Autowired @Qualifier(value = "userDao1") private UserDao userDao; public void add(){ userDao.add(); System.out.println("service add.."); } }
2. Common attribute injection @ Value
3. Pure annotation development @ Configuration
You need to completely replace the configuration file, so you need to create a configuration class Config and start package scanning
@Configuration @ComponentScan(basePackages = {"com.autowire"}) public class FullyDemo1 { }
public class FullyAuto1 { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(FullyDemo1.class); UserService service = context.getBean("userService", UserService.class); service.add(); } }
2AOP
- Aspect oriented programming is to enhance methods and reduce the coupling between business logic.
The core is to add new functions without modifying the original code.
0. Class loader
The function of class loader is to read in the class file and define it as a class. Then you can get the instance through newInstance. Its basic functions are similar to reading xml configuration classes.
For a class to be the same, their full class name needs to be exactly the same as the class loader.
1. Custom class loader
//The loader can load Class files in the same path as itself public class MyClassLoader extends ClassLoader{ @Override public Class<?> loadClass(String name) throws ClassNotFoundException{ try { String fileName=name.substring(name.lastIndexOf(".")+1)+".class"; InputStream is=getClass().getResourceAsStream(fileName); if(is==null){ //Classes that are not in the current path, such as the Object class (the parent class of JavaBean), are loaded using the delegation model return super.loadClass(name); }else{ //Classes in the current path, such as JavaBean classes, directly load their Class files by themselves byte[] b=new byte[is.available()]; is.read(b); return defineClass(name,b,0,b.length); } } catch (IOException e) { throw new ClassNotFoundException(); } } }
1. Concept and principle
Process:
- Configuration facet class (enhanced method collection)
- Configure pointcuts
- aop implantation
1. Bottom layer principle
- Aop uses a dynamic proxy approach.
In the first case with interfaces, JDK dynamic proxy is used.
Create a proxy object. The proxy can use all the methods of the original object. At the same time, it can be enhanced. The interface implements the class proxy object.
The second case without interface uses CGLIB dynamic proxy.
A proxy object is actually a proxy object that overrides a subclass
2.jdk dynamic agent
The method is to create a proxy object through the Proxy.newProxyInstance() method.
The first parameter, the class loader of jdk dynamic agent, is the loader of the current class.
The second parameter, the interface array, is used to specify the proxy method
The third parameter, the actual proxy object, is used to write the enhancement method
public class Typical { public static void main(String[] args) { // Interface of proxy method Class[] interfaces={UserDao.class}; UserDao userDao = new UserDaoImp(); UserDao instance = (UserDao) Proxy.newProxyInstance(Typical.class.getClassLoader(), interfaces, new UserProxy(userDao));//Generate proxy objects with proxy object classes, instance.add(1,2); } } class UserProxy implements InvocationHandler {//Enhancement method, the parameter is the object to be represented private Object object; UserProxy(Object userDao){ object = userDao; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Before executing the method.."); Object invoke = method.invoke(object, args); System.out.println(invoke); System.out.println("After executing the method.."); return invoke; } }
2. Terminology
-
Connection point: enhanced method.
-
Entry point: actually enhanced method
-
notice
- Enhanced logic
- Notification type
- Pre notification, before method
- Post notification, after method
- Surround notification,
- Exception notification, handling when an exception occurs
- Final notice, all end notices
-
section
Is an action, which is the process of applying notifications to pointcuts.
AspectJ
spring framework is an AOP operation based on Aspectj. It is an independent AOP framework, which is only used together.
AOP based on AspecJ:
- configuration file
- Annotation based implementation
Required dependencies:
Pointcut expression
- Grammatical structure
execution([Permission modifier][Return type][Class full road strength][Method name][parameter list]); The return type may not be written; execution(*com.example.bean.User.*(..))
Annotation based AspectJ
1. Generate bean s with annotations
Both the proxy object and the proxy object need to be ben
2. Configure the start agent mode Aop
The function of dynamic proxy is to enable some annotations and tags to be recognized by the spring framework.
xmlns:aop="http://www.springframework.org/schema/aop" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
3. Write proxy class (collection of enhanced methods)
- Common pointcuts can be extracted by methods. Pointcut()
@ Before(value="com.AspectJ.proxy.UserProxy.pointCut()") at the same time, the pointcut can also be written as a special class and called through the full class name.
package com.AspectJ.proxy; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; /** * @Author coder * @Date 2021/10/21 13:29 * @Description */ @Component @Aspect public class UserProxy { //Connection points can be extracted by method @Pointcut(value="execution(* com.AspectJ.bean.User.*(..))") public void pointCut(){ } @Before(value="pointCut()") public void before(){ System.out.println("before..."); } @Before(value="execution(* com.AspectJ.bean.User.*(..))") public void before(){ System.out.println("before..."); } @After(value="execution(* com.AspectJ.bean.User.*(..))") public void finaRes(){ System.out.println("after..."); } @AfterReturning(value="execution(* com.AspectJ.bean.User.*(..))") public void after(){ System.out.println("afterReturning.."); } @AfterThrowing(value="execution(* com.AspectJ.bean.User.*(..))") public void ocuurEror(){ System.out.println("error occured.."); } @Around(value="execution(* com.AspectJ.bean.User.*(..))") public void around(ProceedingJoinPoint point) throws Throwable { System.out.println("Surround front.."); point.proceed(); System.out.println("After surround.."); } }
Proxy methods are divided into five categories: pre, post, surround, exception methods and final methods. Execution sequence:
-
Before wrapping.. public void around (proceedingjoinpoint)
-
before
-
method
-
After surround
-
Post
-
final
One field method will interrupt this process, other processes can be skipped, but the final process will not be omitted
-
@Order when there are multiple methods to enhance the content, you can set the priority of the enhancement class,
Compared with the method after enhancing a method, the higher the priority, the more the enhancement method is wrapped outside. The smaller the @ Order(1) value, the higher the priority.
xml based proxy configuration
<bean id="book" class="com.AspectJ.aopxml.Book"/> <bean id="proxy1" class="com.AspectJ.aopxml.ComProxy1"/> <aop:config> <!-- Configure common pointcuts--> <aop:pointcut id="point1" expression="execution(* com.AspectJ.aopxml.Book.*(..)"/> <!-- Configure the aspect class. The aspect consists of enhancement methods and pointcuts. You need to specify the enhancement class first. The aspect is the collection of enhancement methods--> <aop:aspect ref="proxy1"> <aop:before method="before" pointcut-ref="point1"/> </aop:aspect> </aop:config>
Full annotation based configuration
It is necessary to open package scanning and AOP agent with annotations
- Annotation to enable a function: @ EnableAspectJAutoProxy(proxyTargetClass=true)
3.JDBC
1. Required dependencies
- spring-jdbc
- Spring ORM (for integrating other frameworks)
- Spring TX transaction management
- mysql-connector-java
- druid-1.1.9.jar connection pool
2 register druid connection pool
3. Register jbcTemplate template
4. Configure dao and service
Batch processing
- BatchQuery(sql,list); list is a collection of passed parameter values that constitute objects.
Pass a collection of Object [] arrays
4. Concept of services
1. Basic knowledge of affairs
1. Transaction is the basic unit of database operation. Logically, a group of operations either succeed or fail. Method has consistency, atomicity, isolation and persistence for database operation.
2. Characteristics of transactions**ACID** 1. Atomicity 2. Consistency, increase and decrease 3. Isolation, transactions will not affect each other 4. Persistence, a persistent change after database modification.
Transaction means that some things are either done together or not done at all. If an exception occurs halfway, it needs to be rolled back.
How to start a transaction:
-
Open transaction
-
Conduct business logic
-
No exception submission
-
Rollback with exception
Transactions are generally loaded into the service layer. There are two types of Spring transaction management
- Programming transaction management
- Declarative transaction management
- Annotation based
- xml based configuration file
- The bottom layer is AOP operation.
2. Transaction manager operation
1. Configure the transaction manager (annotation based)
-
Under configuring the transaction manager, you need to tell which database connection pool to use
-
To start transaction management, you need to inject data sources
xmlns:tx="http://www.springframework.org/schema/tx" http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:annotation-driven transaction-manager="transactionManager"/>
-
Annotate the methods (or classes) that need to be enhanced
2. Common parameters in transaction annotations
-
Propagation: propagation behavior
Transaction method: the operation that changes the data in the table is the transaction scheme.
Is a call between multiple transaction methods. Methods with transactions call methods without transactions, and methods without transactions call methods with transactions
Transaction propagation has seven behaviors:
- Required: add contains transactions. Calling other methods will automatically use the current transaction. If add has no transaction, a new transaction is created.
- required_new: add calls update. No matter whether add has a transaction or not, it will create a new transaction and suspend the original transaction.
- PROPAGATION_REQUIRED
Spring's default propagation mechanism can meet most business needs. If there are transactions in the outer layer, the current transaction will be added to the outer layer transaction, one committed and one rolled back. If there is no transaction in the outer layer, create a new transaction to execute - PROPAGATION_REQUES_NEW
The transaction propagation mechanism is to open a new transaction every time and suspend the outer transaction. When the current transaction is completed, the execution of the upper transaction is resumed. If there is no transaction in the outer layer, execute the newly opened transaction - PROPAGATION_SUPPORT
If there is a transaction in the outer layer, join the outer layer transaction. If there is no transaction in the outer layer, directly use the non transaction method. Completely dependent on external transactions - PROPAGATION_NOT_SUPPORT
This propagation mechanism does not support transactions. If there are transactions in the outer layer, it will be suspended. After executing the current code, the outer layer transaction will be resumed. Whether it is abnormal or not, the current code will not be rolled back - PROPAGATION_NEVER
The propagation mechanism does not support outer transactions, that is, if there are outer transactions, an exception will be thrown - PROPAGATION_MANDATORY
In contrast to NEVER, an exception is thrown if there is no transaction in the outer layer - PROPAGATION_NESTED
The feature of this propagation mechanism is that it can save state savepoints and roll back the current transaction to a certain point, so as to avoid all nested transactions rolling back, that is, rolling back their own. If the sub transaction does not eat the exceptions, it will basically cause all rollback.
-
Isolation: isolation level of transaction
Data in use is quarantined
There is no impact between multi transaction operations, which is called transaction isolation. Non isolation will cause many problems: dirty reading (one transaction reads the data of another running transaction), non repeatable reading (one uncommitted transaction reads the modified data of another committed transaction, and the data read by uncommitted transactions is different each time), phantom reading (one reads the new record of another transaction for the committed transaction);
Use transaction isolation to solve these problems.
- Read uncommitted
- Read committed
- repeated read is repeatable by default
-
Timeout: timeout
The transaction is committed within the specified time. Otherwise, the rollback is - 1 by default and no operation is performed.
-
readOnly: read only
The default value is false, and only the meaning can be queried.
-
rollbackFor() rollback
Set which exceptions occur for rollback
-
norollbackFor()
Which exceptions do not roll back.
3. Configure transactions based on xml
- Configuring the transaction manager in spring
- Configure notification (enhanced part) TX advice. If it is aspect, configure the agent class and aspect method, and the transaction is configuration notification.
- Configure tangent points and facets.
You don't need to start a transaction because you don't need to scan the transaction and configure it yourself.
4. Full annotation development
- Replace the transaction Bean and implement it through @ Bean,
- @The parameters required by the method specified by bean are automatically injected through the existing bean by default, and the core is injected according to the type
- Start transaction scanning with annotations@ EnableTransactionManagement