Spring5 quick start
A lightweight open source J2EE application development program
Features:
- Convenient for decoupling
- Support aop
- Convenience test
- Convenient integration framework
- Reduce the API development difficulty
- Convenient transaction operation
IOC inversion of control
Turn the object creation process over to Spring to manage, reducing coupling
The underlying principle
XML parsing, factory schema, reflection
Process:
- Create objects using XML
- Parse using XML parsing techniques
- Create objects through reflection
- Class clazz = class.forname (parsed Class path);
- Return (class name) clazz.newinstance ();
At the bottom of the IOC container is the object factory
Spring provides two ways to implement an IOC container (two interfaces) :
1.BeanFactory: (does not create objects when loading configuration files, only creates objects when using them)
The basic implementation of the IOC container is an interface used internally by Spring and is not available to developers
2.ApplicationContext (objects are created when the configuration file is loaded)
Beanfactory is a subinterface to the BeanFactory to provide more power for developers to use.
Implementation class: Outside the chain picture archiving failure, the source station might be hotlinking prevention mechanism, proposed to directly upload picture preserved (img – xkK0axEE – 1626155346282) (.. /.. / AppData/Roaming/Typora/Typora – user – images/image – 202 10712180533330.png)]
bean-managed
Based on XML
Create an object
(1) Bean label
Id: indicates the unique global id
Class: indicates the class full path
Properties into
Set method injection
<! Spring = set ();
<bean id="book" class="com.zero.spring5.Book">
<! Name: the name of the property in the class value: the value injected into the property -->
<property name="bname" value="Hello"></property>
<property name="bauthor" value="World"></property>
</bean>
Copy the code
Have the cords structure
<! -- (2) Spring mode: construct injection attribute with parameter -->
<bean id="orders" class="com.atguigu.spring5.Orders">
<constructor-arg name="oname" value="Hello"></constructor-arg>
<constructor-arg name="address" value="China!"></constructor-arg>
</bean>
Copy the code
Into a null value
<bean id="book" class="com.atguigu.spring5.Book">
<! -- (1) null -->
<property name="address">
<null/><! Add a null tag to the property -->
</property>
<! -- (2) special symbol assignment -->
<! -- The attribute value contains the special symbol a to escape <>. > CDATA -->
<property name="address">
<value><! [CDATA [< < Nanking > >]] ></value>
</property>
</bean>
Copy the code
Injecting external beans
<! Service and DAO object creation -->
<bean id="userService" class="com.zero.spring5.service.UserService">
<! Create userDao bean tag id -->
<property name="userDao" ref="userDaoImpl"></property>
</bean>
<bean id="userDaoImpl" class="com.zero.spring5.dao.UserDaoImpl"></bean>
Copy the code
Inject inner classes and cascading assignments
<! - internal bean -- -- >
<bean id="emp" class="com.zero.spring5.bean.Emp">
<! Set two general properties -->
<property name="ename" value="Andy"></property>
<property name="gender" value="Female"></property>
<! -- Set object type properties -->
<property name="dept">
<bean id="dept" class="com.zero.spring5.bean.Dept"><! Inner bean assignment -->
<property name="dname" value="Propaganda Fehead"></property>
</bean>
</property>
</bean>
<! -- Method 1: Cascade assignment -->
<bean id="emp" class="com.zero.spring5.bean.Emp">
<! Set two general properties -->
<property name="ename" value="Andy"></property>
<property name="gender" value="Female"></property>
<! -- Cascade assignment -->
<property name="dept" ref="dept"></property>
</bean>
<bean id="dept" class="com.zero.spring5.bean.Dept">
<property name="dname" value="Public relations Fehead"></property>
</bean>
<! -- Cascade assignment -->
<bean id="emp" class="com.zero.spring5.bean.Emp">
<! Set two general properties -->
<property name="ename" value="jams"></property>
<property name="gender" value="Male"></property>
<! -- Cascade assignment -->
<property name="dept" ref="dept"></property>
<property name="dept.dname" value="Technology Fehead"></property>
</bean>
<bean id="dept" class="com.zero.spring5.bean.Dept">
</bean>
Copy the code
Inject collection properties
<! -- (2) Configure in the Spring configuration file -->
<bean id="stu" class="com.zero.spring5.collectiontype.Stu">
<! -- Array type property injection -->
<property name="courses">
<array>
<value>Java classes</value>
<value>Database course</value>
</array>
</property>
<! --list type attribute injection -->
<property name="list">
<list>
<value>Zhang SAN</value>
<value>Li si</value>
</list>
</property>
<! -- Map attribute injection -->
<property name="maps">
<map>
<entry key="JAVA" value="java"></entry>
<entry key="Python" value="php"></entry>
</map>
</property>
<! -- Set type attribute injection -->
<property name="sets">
<set>
<value>MySQL</value>
<value>Redis</value>
</set>
</property>
</bean>
Copy the code
Inject a collection of object types
<! Create multiple course objects -->
<bean id="course1" class="com.zero.spring5.collection.Course">
<property name="cname" value="Spring5 framework"></property>
</bean>
<bean id="course2" class="com.zero.spring5.collection.Course">
<property name="cname" value="MyBatis framework"></property>
</bean>
<! Insert list collection type, value is object -->
<property name="courseList">
<list>
<ref bean="course1"></ref>
<ref bean="course2"></ref>
</list>
</property>
Copy the code
FactoryBean
There are two types of beans in Spring, plain beans and factoryBeans
- Plain beans: Bean types defined in configuration files are return types
- Factory Beans: The Bean type defined in the configuration file can be different from the returned type
public class MyBean implements FactoryBean<User>{
@Override
public Object getObject(a) throws Exception {
return null;
}
@Override
// Determine the type to return
publicClass<? > getObjectType() { User t =new User(){{
setId(1);
}}
return t;
}
@Override
public boolean isSingleton(a) {}}//test
<bean id="myBean" class="com.atguigu.spring5.collectiontype.myBean">
ApplicationContext context = new ClassPathXmlApplicationContext("example.xml");
User user = context.getBean("myBean",User.class);
System.out.println(user);
Copy the code
The scope of the Bean
By default, objects created in Spring are singleton (object addresses are equal).
<bean id="myBean" class="com.zero.spring5.collectiontype.myBean" scope="singleton"
Multi-instance object creation
<bean id="myBean" class="com.zero.spring5.collectiontype.myBean" scope="prototype"
scope:
Singleton: single instance
Prototype: multiple instances
Requst: A request
Session: indicates a session
The life cycle of the Bean
The process from creation to destruction of an object
(1) Create bean instance with constructor (no arguments)
(2) Set values for bean properties and references to other beans (SET)
(3) Pass the bean instance to the bean post-processor method
(3) Call the bean’s initialization method (initialization configuration required)
Create the initialized method in the bean class
(3) the method of passing the bean instance to the bean post-processor
(4) Get the bean
(5) When the container is closed, call the bean destruction method (configure the destruction method).
Create destruction methods in the bean class
Use ((ClassPathXmlApplicationContext) context). The close () method to trigger the destroy method, so as to destroy the object
Create a post-processor
public class MyBean implements BeanPostProcessor {
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Execute before initializing method")
return bean;
}
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Execute after initializing method")
returnbean; }}// Configure this class in XML
<bean id="myBean" class="com.atguigu.spring5.collectiontype.myBean">
Copy the code
XML auto-assembly
Automatic assembly according to the specified assembly rule (attribute name or attribute type)
<bean id="myBean" class="com.atguigu.spring5.collectiontype.myBean" autowire="byName">
<bean id="bean" class="com.atguigu.spring5.collectiontype.myBean" autowire="byName">// Automatic assembly by type is the same, but an error is reported when there are multiple instances of the same typeCopy the code
Import the external properties file
<context:property-placeholder location="classpath:jdbc.properties"/>// The jdbc.properties file is introduced<bean id="datasource" class= "com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value = "${prop.driverClass}"></property>
<property name="url" value = "${prop.url}"></property>
<property name="username" value = "${prop.username}"></property>
<property name="password" value = "${prop.password}"></property>
</bean>
Copy the code
Annotation-based
@service
@componet
@controller
@reposity
Injection of objects
Autowired: Auto assemble by type
Qualifier: Injection based on attribute names is used in conjunction with autowired
@resource: Inject by type, or by name
Inject common types:
@Value
Component Scanning Configuration
// Sets what not to scan<context:component-scan base-package="Com. Zero">
<context: exclude-filter type="annotation"
expression="com.zero.Controller"/>
</context:component-s>// Sets which packets to scan<context:component-scan base-package="Com. Zero" use-default-filters="false">
<context: include-filter type="annotation"
expression="com.zero.Controller"/>
</context:component-s>
Copy the code
AOP is faceted
Feature enhancements without modifying the source code
The underlying principle
1.AOP uses dynamic proxies underneath
With interfaces (enhancements to interface implementation classes) : Use JDK dynamic proxies
Create a proxy object for the interface implementation class,
Create the Proxy method using newProxyInstance in the Proxy class in the JDK
Parameter 1: class loader
Parameter 2: the class of the enhanced method, the interface that this class implements, supports multiple interfaces
Parameter 3: Implements InvocationHandler, creates proxy objects, and writes enhanced methods
public class JDKProxy {
public static void main(String[] args) {
// The interface that needs to be implemented by the enhanced method can be multiple
Class[] interfaces = {UserDao.class};
UserDao o = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader()/* Class loader */, interfaces/* Enhanced method implementation interface */.new UserDaoProxy(new UserDaoImpl()) /* Proxy object class */);
System.out.println(o.add(1.2)); }}class UserDaoProxy implements InvocationHandler{
private Object obj;
// Pass the proxy object that is created (implementation class)
public UserDaoProxy(Object obj) {
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// before the method
System.out.println("Method before executing:" + method.getName() + "Parameter:" + Arrays.toString(args));
// The original logic
Object invoke = method.invoke(obj, args);
// After the method
System.out.println("Execute after method execution...");
returninvoke; }}Copy the code
If there is no interface: Use the CGLIB dynamic proxy
Creates a proxy object for subclasses of the current class
AOP terminology
The join
Which methods in a class can be enhanced are called join points
The breakthrough point
The methods that are actually enhanced are called pointcuts
Notification (enhanced)
The part of logic that is actually enhanced is called notification
There are many types of notifications
Pre notice
The rear notice
Surrounding the notification
Abnormal notice
Final notice
section
Is an action, and the process of applying advice to a pointcut is called aspect
AOP operation
Implement AOP operations based on AspectJ
Pointcut expression
Indicates which method in which class is enhanced
Execution ([permission modifier][return type][class full path][method name] ([method parameter list]))
Execution (* com. Zero. Service. UserDao. Add (1, 2))
Annotation based implementation
1. Create a class in which methods are defined and enhanced
2. Create enhancement classes (write enhancement logic)
Add the @aspect annotation to the enhanced class to generate the proxy object
3. Enable proxy object generation in the configuration file
4. Configure different types of notification
Add notification type annotations and write pointcut expressions above the methods that enhance the class as advice
@Component
public class User {
public void add(a) {
System.out.println("add ........"); }}/ / class
@Component
@Aspect
public class UserProxy {
// Pre-notification
@Before(value = "execution(* com.example.spring5.service.aop.User.add(..) )"
public void before(a) {
System.out.println("before.......");
}
// after the method is executed
@After(value = "execution(* com.example.spring5.service.aop.User.add(..) )"
public void after(a) {
System.out.println("after");
}
// After the method return value is returned
@AfterReturning(value = "execution(* com.example.spring5.service.aop.User.add(..) )"
public void afterRtreuning(a) {
System.out.println("afterReturning");
}
/ / exception
@AfterThrowing(value = "execution(* com.example.spring5.service.aop.User.add(..) )"//
public void afterThrowing(a) {
System.out.println("afterThrowing");
}
@Around(value = "execution(* com.example.spring5.service.aop.User.add(..) )" // Method before and after execution
public void arount(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("Before enhancement...");
proceedingJoinPoint.proceed();// Implement the enhanced method
System.out.println("Enhanced..."); }}Copy the code
Common pointcut extraction
// Pointcut extraction
@Pointcut(value = "execution(* com.example.spring5.service.aop.User.add(..) )"
public void point(a) {}// Pre-notification
@Before(value = "point()")
public void before(a) {
System.out.println("before.......");
}
Copy the code
Transaction management:
@transitional Transaction parameters
Propagation: Parameter propagation
- REQUEIRED: If there is a transaction running, the current method is run within this transaction, otherwise, a new transaction is started and run within its own transaction
- REQUEIRED_NEW: The current method must start a new transaction and run within its own transaction, and should suspend it if a transaction is running
- SUPPORTS: If there is a transaction running, the current method will run in that transaction, otherwise it will not run in the transaction
- NOT_SUPPORTS: The current method should not run in a transaction. If there is a running transaction, suspend it
- MANDATORY: The current method must run inside a transaction and throw an exception if no transaction is running
- NEVER: The current method should not run in a transaction, and throws an exception if a transaction is running
- NESTED: If a transaction is running, the current method should run inside a NESTED transaction of that transaction, or start a new transaction and run inside its own transaction
Ioslation: transaction isolation level
Three reading questions:
- Dirty read: an uncommitted transaction reads data from another uncommitted transaction
- Unrepeatable read: an uncommitted transaction reads data from another committed transaction
- Phantom read: an uncommitted transaction reads data added by a committed transaction
Four isolation levels:
- READ UNCOMMITED: The READ is not committed
- READ COMMITED: Indicates that a file has been READ
- REPEATABLEED: repeatable read (mysql default, solve dirty and unrepeatable read)
- SERIALIZABLE: serialization
Timeout: indicates the timeout period
Transactions need to be committed within a certain amount of time and rolled back if they are not
Readonly: Indicates whether it is read-only
Default false, set to true to restrict us to read-only
RollbackFor: rolled back
Sets which exceptions to query for transaction rollback
norollbackFor
Sets which exceptions do not roll back transactions
New features
- The default logging framework changed from Log4j to log4j2
- @nullable: can be used for methods, attributes, and parameters. Method return values can be null, attribute values can be null, and parameter values can be null
- Support for functional programming
- Support junit5
- Webflux: An asynchronous non-blocking framework
- Springmvc is imperative programming, and springwebfux is asynchronous responsive programming