Today’s sharing started, please give us more advice ~
IOC creates objects in two ways
1. No-parameter construction mode
Sprirng creates a new object using a no-argument construct and then uses the set method to inject the property, which is represented as a property assignment in bean.xml.
If there is no set method in the entity class, property is used to assign a value to the property.
2. Parametric construction
Add a parameterized constructor to the entity class (parameterless constructor is included by default).
Modify the bean.xml method
As a recap of Java knowledge, when Java objects are created, the no-parameter constructor is included by default, but the default no-parameter constructor is invalid after the parameter constructor is written. In this case, you need to write a no-parameter constructor by hand.
The spring configuration
1 Alias Configuration
Configuration rules for Spring aliases
Similar to mybatis, which is used this way.
After the alias is configured, it is possible to obtain object instances through the alias in Java code.
2 the bean configuration
This configuration file is explained in Java code
Hello hello = new Hello();
hello.setName(Spring);
3 Multi-team cooperation Import
If you want to use XML files written by someone else in your team development, you can do so by importing them so that you can use the attributes of someone else’s bean in your own bean.
Dependency injection
Dependency injection, Spring’s way of implementing IOC, allows you to inject bean property values in a variety of ways.
Parameter constructor injection
Constructor injection was implemented in 4
2 set injection
The set method must be capitalized with the first letter of the set + attribute. If the attribute is of Boolean type, there is no set method, is.
Create an entity class for testing
Student.java
Because the student object contains the object Address
Address.java
Constant injection (common data types such as Inter, String, double, etc.)
Objects into
Here ref is a reference.
An array of injection
The list into
The map into
The set injection
property
Null injection
The results of
3 Use namespace injection
P namespace injection: constraint files are required in header files
C namespace injection: constraint files are required in header files
4 Scope of Bean
The Singleton Singleton
There will only be one shared bean instance in the Spring IoC container, and all requests for a bean will only return the same instance of the bean as long as the ID matches the bean definition.
Prototype
When a bean is scoped to Prototype, a bean definition corresponds to multiple object instances. A prototype-scoped bean results in a new bean instance being created each time the bean is requested.
Request
When the scope of a bean is Request, it means that in an HTTP Request, one bean definition corresponds to one instance. That is, each HTTP request has its own bean instance, which is created from a bean definition.
<bean id=”loginAction” class=cn.csdn.LoginAction” scope=”request”/>
Session
When the scope of a bean is Session, it means that in an HTTP Session, one bean definition corresponds to one instance.
Bean assembly and management
In many cases, we need to use another class object in one class, but we’ve left the creation of the object to Spring.
So we need to assemble the object properties of our class in some way, called object injection, which works in a similar way to the injection of property values.
1 is assembled by ref
We now have three classes
We had to inject three classes into the SpringIOC container.
And the assembly of Cat and Dog into Peoson can be used normally, similar to the injection of attribute values.
Essentially, the Cat and Dog instances are taken out of IOC and assigned to the Peoson class.
This manual assembly is also convenient, but a much easier way to simplify the process – > autowire automatic assembly.
We can implement autowiring using XML configuration or annotations.
2 XML Configuration Automatic configuration
2.1 byName
Only through this simple automatic assembly can achieve the previous function. It automatically matches the bean ID with the name of the set method property.
2.2 byType
In the same way, this is auto-assembled by class type. By type, only one instance of an object of the same type can exist at the same time.
Automatic assembly using annotations
Annotations are being supported in jdk1.5 and fully supported in spring2.5.
The first step is to assemble the bean instance using ref references.
In the second step, we use autowire to implement bean autowire.
The third step is to annotate the autowiring.
Using annotations requires some additional configuration.
Introduce the context header in the Spring configuration file.
Enable attribute annotation support!
context:annotation-config/
3.1 Autowired
@autoWired is automatically configured by type and does not support ID matching.
Need to import the spring-AOP package! (Already imported in MVC JAR package)
Usage:
Entity class:
bean.xml
Autowired matches byType by default, which can be understood as a byType matching rule
Because the annotation method does not use the set method for injection, you can omit the set method in the entity class.
3.2 @ the Qualifier
@autoWired is Autowired by type, and @Qualififier is Autowired by byName
@Qualififier cannot be used alone.
Usage:
Entity class:
bean.xml
In this way, you can achieve the same functionality as ref.
It can also be written on the set method.
Autowired(required = false) @autowired (required = false) @autowired (required = false) @autowired (required = false) @autowired (required = false)
Use another annotation method for automatic configuration
4.1 @ the Resource
If @resource has a specified name attribute, byName lookup assembly is performed according to this attribute.
Secondly, the default byName method is used for assembly.
If all else fails, byType is used for automatic assembly.
Entity class:
bean.xml
In this way, the function of ref can also be implemented.
It can be written to the set method ** just like ** @autowired.
5. Similarities and differences between @autowired and @resourse
It can also be written to an attribute or set method and used with the attribute to achieve the function of ref.
@autowired is part of the Spring specification and matches byType by default
@resource (belongs to J2EE callback), which is matched by byName by default.
Annotations to develop
In Spring, you can use XML to inject beans, assemble beans, and inject bean attribute values. But actual development with annotations is really cool, and the use of XML for bean management and assembly will be phased out.
1 Preparations
After annotating the bean, you can also annotate the bean for automatic injection of properties.
Front environment:
Bean injection and property value assignment
Entity class:
You can inject directly on property values, but it is recommended to inject on set methods when there is a set method.
Inject property values directly via @value (“”), as in the bean.
The @Component annotation works like the bean tag in the bean.xml file, meaning that the class is managed by the Spring container.
Injecting entity classes into the IOC container in this way eliminates the need to inject entity classes in bean.xml.
3 Component derived annotations
These annotations are a substitute for the configuration step in the configuration file. More convenient and fast!
@Component three derived annotations
For better layering, Spring can use three other annotations, which do the same thing and which are currently used.
@ Controller: * * * * web layer
@ Service: * * * * the Service layer
@ Repository: * * * * dao layer
By writing these annotations, you hand the class over to the Spring-managed assembly!
Automatic assembly of beans
A previous blog post wrote about using one bean within another.
In this way, the assembly of beans is realized. In conjunction with the previous content, we will be able to manage and inject beans without XML configuration files altogether.
Annotation method, quick and elegant
Together, this completes all the functionality of class and attribute injection in bean.xml.
5 Scope @scope
Singleton: By default, Spring creates this object in singleton mode. Shut down the factory and all objects are destroyed.
Prototype: Multiple example mode. Close the factory and all objects will not be destroyed. The internal garbage collection mechanism will collect.
6 summary
The use of full annotations is a mainstream way of only using, and it is more commonly used in the subsequent SpringBoo. But the way XML is understood helps us use and understand the evolution of the framework.
XML way
Annotation way
Dependency injection is just one implementation of IOC, and we want to leave object creation and management to the Spring container. This will allow us to manage classes without making complex code changes, rather than using injections to change them all at once
Such as:
private SqlService sqlService = new MySqlServiceImpl()
If we need to change the implementation class, we need to re-new an object
private SqlService sqlService = new OracleServiceImpl()
But dependency injection is implemented in a different way
This saves us the extra overhead of creating a new object.
The proxy pattern
The underlying idea of AOP for aspect programming is the proxy pattern. Understanding the proxy pattern is very helpful to understand THE AOP pattern.
The proxy mode is divided into:
Static agent
A dynamic proxy
Use UML diagrams to describe this briefly
1 Static Proxy
Static proxy role analysis
Abstract roles: Typically implemented using interfaces or abstract classes
Real role: The role being represented
Proxy role: Proxy for the real role; After a real role is represented, it usually does some ancillary operations.
Customer: Use the agent role to perform some operations.
Static proxy Example one:
Abstract role Rent
Real character Host
Customer client
In the agent mode, the real role and the agent role jointly realize the abstract interface of renting a house. The real role has the right to rent a house, because the agent role finds the real role, and the real role gives the right to rent a house to the agent.
** Advantages: ** The agent character can provide additional functions in addition to the function of renting a house, such as signing a contract, viewing a house, etc., which the real character does not want to do, but does not affect his own renting function.
Static proxy Example 2:
Abstract interface UserService
The real role is UserServiceImpl
The proxy role UserServiceImplProxy
The client
** And the previous static proxy case I, through the proxy role way, in the realization of the real role function on the basis of, without affecting the addition of some proxy functions.
This is also the underlying implementation mechanism of AOP
2 Dynamic Proxy
Just like with mybatis, when there are many types of paging, we don’t want to add a paging class for each type, so we use generics to match the return of different types of data.
The role of a dynamic proxy is the same as that of a static proxy.
The proxy class for dynamic proxy is dynamically generated. The proxy class for static proxy is written in advance
Dynamic proxy can be divided into two types: dynamic proxy based on interface and dynamic proxy based on class
Interface based dynamic proxy —-JDK dynamic proxy
Class-based dynamic proxy – Cglib
Now more use is javasist to generate dynamic proxy. Baidu javasist
There are two classes you need to know about dynamic proxies in the JDK
Core: InvocationHandler and Proxy.
In this way, we can dynamically represent objects like Rent.
In addition to the proxy method, sometimes we want to be able to implement a proxy for all objects. In this case, we can change Rent to Object, so that we can proxy for all Object types.
Usage:
3 summary
Like utility classes, dynamic proxies can be handy for dynamically performing tasks that require changing requirements and are frequently used.
AOP
AOP as one of the two core of Spring, namely, section-oriented programming, its underlying implementation is proxy mode, horizontal way to strengthen the existing functions, so that business logic and functional code better decoupling.
1 Aop’s role in Spring
Crosscutting concerns: Methods or functions that span multiple modules of an application. That is, the part that is irrelevant to our business logic, but that we need to focus on, is crosscutting concerns. Such as logging, security, caching, transactions…
ASPECT: A special object whose crosscutting concerns are modularized. That is, it is a class.
Advice: Work that must be done by the aspect. That is, it is a method in a class.
Target: indicates the notified object.
Proxy: Object created after notification is applied to the target object.
PointCut: The definition of the “place” where a tangent notification is executed.
Join Point: The execution point that matches the pointcut.
In SpringAOP, crosscutting logic is defined through Advice, and there are five types of Advice supported in Spring:
2. Use of AOP
Environment: Jar packages need to be imported
The first way
By inheriting existing methods, and then using an AOP configuration file, you set the cuts and the way the wrap is executed
Abstract interface UserService
Real Character (landlord)
In this way, we implement similar functionality to dynamic proxy.
The second way
Sometimes the proxy methods provided by it may not be suitable for our functional needs, and we want to implement the proxy functionality by customizing the proxy class rather than through its existing methods.
User-defined Proxy class Proxy
The third way
This is done through annotations
bean.xml
Integration of mybatis
Mybatis provides efficient management of database operations, while Spring provides a new way to create and use objects.
Integrating MyBatis combines myBatis data manipulation with Spring inversion of control.
Import related JAR packages
Transform mybatis
Mybatis has User entity class, UserMapper interface, usermapper. XML, and mybatis-config.xml.
The main thing is to modify mybatis-config file, we need to transfer some myBatis database connection operations to Spring operation together.
Create a new spring-config.xml file
In this file, we put together the Sqlsession fetch, the connection to the database, and some configuration of Mybatis.
Operating sqlsession
Use getBean () in the test class to get the session
The Session is injected through a UserMapperImpl implementation class. (specification)
The official documentation specification uses the second approach, which is more in line with Spring dependency injection.
To optimize the
Separate the configuration from normal bean injection by importing
Sqlsession retrieval is further simplified.
Mybatis – Spring version 1.2.3 or above can be used.
SqlSessionDaoSupport = getSqlSession(); Inject SqlSessionFactory directly into UserMapperIml in bean management.
Inject the sqlSessionFactory.
Separate UserMapperImpl into the Service layer
If you have a usermapper. XML and then you have a UserMapperImpl, the logic is a bit confusing. You can separate the UserMapperImpl and create a service layer. Session fetching is done at this level.
Inject session type
Inherited SqlSessionDaoSupport class
Getting sesission is further simplified:
As we acquire sessions more, we want to acquire sessions in a more efficient and manageable way.
The Spring framework provides an automatic scanning for MapperScannerConfigurer, which automatically infuses sessions into all Mappers under the package name by setting the class’s properties and automatically scanning specified packets.
We can directly obtain mapper to operate, and give the session capture to Spring encapsulation.
Usage:
Configuration file:
It needs to manually set two properties to inject session for the specified package name.
call
private UserMapper userMapper;
It can be used directly.
The transaction
A more detailed explanation of transactions is shown in another blog post of mine
Transaction is very important in the process of project development, involving the consistency of data, not to be careless!
Transaction management is an essential technology in enterprise application development to ensure data integrity and consistency.
A transaction is a series of actions that are treated as a single unit of work, all of which either complete or do not work.
Transaction four properties ACID
1. Atomicity
A transaction is an atomic operation, consisting of a series of actions, and the atomicity of the transaction ensures that the actions either complete completely or do not work at all.
2. Consistency
Once all transaction actions are completed, the transaction is committed. Data and resources are in a consistent state that meets business rules.
3. Isolation
It is possible for multiple transactions to process the same data at the same time, so each transaction should be isolated from others to prevent data corruption.
4. Durability
Once a transaction completes, the results are unaffected by whatever errors occur to the system. Typically, the results of a transaction are written to persistent storage.
Role of transactions
When we manipulate data, we perform add, delete, change and review operations in the same method, and we want to invalidate all operations in that method if one of our operations goes wrong. Spring provides a great management feature called transaction management.
Use of transactions
Introduce AOP and TX headers
Define as a transaction manager to bind data sources to
Configure notification rules for transactions in detail
Weave in using AOP
Today’s share has ended, please forgive and give advice!