Hello, today I want to share Spring with you. Please take out your little book and write it down.
Introduction of the Spring
Layered Java SE/EE application Full-Stack lightweight open source framework with IOC (inversion of control) and AOP (aspect oriented programming) as the kernel
It can integrate many third party frameworks and class libraries in the open source world, and gradually become the most used Java EE enterprise application open source framework
Advantage:
Easy decoupling: By using the IOC container, the dependencies between objects are handed over to Spring to avoid over-coupling of the code
Support for AOP programming
Declarative transaction support: Declarative flexible transaction management reduces unnecessary transaction management code
Convenient test
Easy integration of excellent frameworks
Reduce the difficulty of using Java EE apis
Source code is a learning model
Basic Spring development steps:
Import jar package coordinates
Create a Javabean
Create the configuration file applicationContext.xml
Configuration file type for configuration
Create the ApplicationContext object and call the getBean() method
IOC development for Spring
Spring configuration file
Bean label basic configuration
The object for configuration is handed over to Spring for creation, and the no-parameter construct in the class is invoked by default, or the creation fails if there is none
Basic attributes:
Id: Unique identification of the Bean instance in the Spring container
Class: Fully qualified name of the Bean
Other attributes:
Scope: object scope, singleton (singleton, default), prototype (multiple), Request, Session, Global Session
When scope property is singleton:
Instantiation timing: When the Spring core file is loaded (when the configuration file is loaded)
When scope is prototype:
Instantiation timing: when getBean() is called
Init-method: Specifies the name of the initialization method in the class
Destroy-method: Specifies the name of the destruction method in the class
Beans can be instantiated in three ways:
Instantiation of the no-parameter constructor (master) :
Factory static method instantiation (understanding) :
Public Class StaticFactoryBean{public static UserDao createUserDao () {return new UserDaoImpl(); }}
Factory instantiation method instantiation (Understanding) :
Public class DynamicFactoryBean{public UserDao createUserDao () {return new UserDaoImpl(); }}
Dependency injection for beans:
Create the UserService. The UserService internally calls the UserDao’s save() method.
Leave the creation of UserServiceImpl entirely to Spring
Get the UserService from the Spring container to operate
Because the UserService and UserDao are both in the Spring container and the final application uses the UserService directly, it is possible to set the UserDao inside the UserService in the Spring container.
Dependency injection for beans:
1. Set method injection:
UserServiceImpl
// Add the setUserDao method in UserServiceImpl
pubic class UserServiceImpl implements UserService{
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
Copy the code
}
ApplicationContext. The name attribute represents the userService xmlproperty set method in the second half of the userDao
<property name="userDao" ref="userDao"/>
Copy the code
Controller
public class UserController {
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) app.getBean("userService");
userService.save();
}
Copy the code
}
Note: If the Controller layer does not create the UserService through the Spring configuration file, but instead creates a new UserService by itself, The new UserService will not create or inject a DaoUser object through the set method, so using the Userdao.save method will generate a null pointer exception
P namespace injection (set)
Extension: introduces the p namespace writing method, which is not commonly used
xmlns:p=”springframework.org/schema/p”
Constructor injection: Create a parameter construct
<constuctor-arg name="userDao" ref="userDao"/>
Copy the code
The dependency injection data type of the Bean (all in set mode)
1. Create private objects name and age in UserDaoImpl for common data types such as String, and create set methods
<property name="name" value="zhangsan"/>
<property name="age" value="18"/>
Copy the code
2. Reference data types (already available above)3. Set data types such as list
<property name="strList" value="zhangsan">
<list>
<value>123</value>
<value>123</value>
<value>123</value>
</list>
</property>
Copy the code
Such as map < String, User >
For example, key-value pairs of type properties <String,String
<property name="props">
<props>
<prop key="p1">aaa</prop>
<prop key="p2">bbb</prop>
</props>
</property>
Copy the code
Import other configuration files and develop them by module: You can import other configuration files in the main configuration file by import. If configuration conflicts occur, they are overwritten according to the sequence in which configurations are imported
A simple memory
Note the name of the property in the configuration file
Insert the value of the property in the second half of the set method (setUserDao => userDao).
Using the constructor, name: the name of the argument to be passed (passing userDao => userDao)
Dependency injection reference object: Configure the REF property
Dependency injection common objects: Configure the value property (String is also directly configured with value)
Dependency injection common objects of a collection type are configured with different properties depending on the collection type
For example, the injection of List type needs to be configured with attributes, and then the corresponding object is configured in the List attribute. Map-type injection is configured with properties, which consist of key-value pairs, so the properties are configured
Spring related API
ApplicationContext: an interface type that represents the ApplicationContext and can be instantiated to obtain Bean objects in the Spring container
ApplicatioContext implementation class:
ClassPathXmlApplicationContext: from the root class loading configuration file, it is recommended to use
FileSystemXmlApplicationContext: load the configuration file from the disk path, configuration files can be in the disk at any position, not commonly used
AnnotationConfigApplicationContext: use the annotation configuration container object, use to create the Spring container, such as to read the comments
GetBean () method:
When the parameter type is String, the Bean instance is obtained from the container based on the Bean ID, and Object is returned
When the parameter type is Class, the Bean instance is fetched from the container by type. It cannot be used when there are more than one Bean of the same type in the container
Spring configuration data source (connection pool)
Development steps:
Import data source coordinates and database driver coordinates
Creating a data source object
Sets the base connection data for the data source
Get and return connection resources using data sources
Configure the data source raw (undecoupled)
Read the jdbc.properties configuration file to create the connection pool (decoupled, but not having Spring create the data source object for us)
Configure the data source using Spring
Delegating the creation of the DataSource to the Spring container (uncoupling, but unclear configuration file division)
DataSource has no parameter constructor. Spring instantiates objects using the parameter constructor by default
DataSource also needs to set the database connection information using the set method, which Spring can inject
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
Copy the code
Extract JDBC configuration files to configure data sources (decouple, while each configuration file has a clear division of labor, Applicationcontext.xml loads the jdbc.properties configuration file to obtain connection information. Location =” Class load path :xxx.properties”
Spring Annotation development (mainstream important)
Annotations replace XML configuration
Steps:
Annotate the class first
Enabling Component Scanning
Spring original notes
When developing with annotations: You need to configure component scanning in applicationContext.xml, specifying that beans under that package and its subpackages need to be scanned to test classes, fields, and methods that need to be configured with annotations
<context:component-scan base-package=”com.itheima”/>
Spring instantiation using the @Component or @Repository identity UserDaoImpl
//
//@Component(“userDao”)
@Repository(“userDao”)
public class UserDaoImpl implements UserDao {
public void save() { System.out.println("save running..." ); }Copy the code
}
Use @Component or @service to identify UserServiceImpl for Spring instantiation
String injection using @value
Inject the userDao using @autowired or @Autowired+@Qualifier or @Resource
(Annotation injection allows you to assign a value to a target directly through reflection without using set.)
Use Scope to annotate the Scope of the Bean
@Scope(“singleton”)
public class UserDaoImpl implements UserDao{
}
Pay attention to
When you just write Autowired before dependency injection, Spring matches that data type from the Spring container,
For example, you currently need a userDao object, and Spring just injected the UserDaoImpl default Singleton, so you can use it, but if you have more than one object, you will have problems
That is, inject by type: @autowired; Inject by ID: @autowired + @Qualifier(” XXX “)
Using annotations to inject objects allows you to find and assign values to the target object through reflection without using set methods
@value (“${jdbc.driver}”)Value is used in conjunction with SpEL to inject common variables in Spring configuration files
Spring new annotation
Using the original annotations does not completely replace the XML file; new annotations are required
Non-custom Bean configuration:
Load the configuration of the properties file: context:property-placeholder
Scan component configuration: context:component-scan
Import other files:
@configuration // Specify that this class is a Spring Configuration class. Load the annotations for this class
//<context:component-scan base-package=”com.itheima”/>
@ComponentScan(“com.itheima”) // Specifies the configuration for scanning components
@ Import ({DataSourceConfiguration. Class}) / / Import other configuration classes, is an array
public class SpringConfiguration {
}
Test class AnnotationConfigApplicationContext class specifies the configuration class name is used, obtain ApplicationContext object
public class controller {
public static void main(String[] args) {
ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
UserService userService = app.getBean(UserService.class);
userService.save();
}
Copy the code
}
Spring integration Junit
Within each test class, each test method will have the following two lines of code
ApplicationContext app = new ClassPathXmlApplicationContext(“bean.xml”);
Object o = app.getBean(xxx.class);
These two lines of code are used to retrieve the container. If they are not written, they indicate a null pointer exception, so they cannot be deleted easily
Solution: Let SpringJunit create the Spring container, but tell it the name of the configuration file, and inject the beans that need to be tested directly into the test class
Spring inherits Junit steps:
Import the Spring integration Junit coordinates: spring-test
Replace the original run-time with the @runwith annotation
Use @contextConfiguration to specify a configuration file or configuration class
Inject objects to be tested using @AutoWired
Use the @test creation method to Test
Spring AOP development
Section-oriented programming realizes unified maintenance of program functions by means of precompilation and run-time dynamic proxy
Advantages: during the operation of the program without modifying the source code under the condition of functional enhancement, reduce repeated code, improve efficiency and easy maintenance
Implementation: The bottom layer is implemented through Spring’s dynamic proxy technology
Common dynamic proxy techniques:
JDK proxy: Dynamic proxy technology based on interfaces
Cglib proxy: Dynamic proxy technology based on superclass
JDK dynamic proxy
Cglib dynamic proxy
AOP related concepts
The underlying AOP implementation of Spring encapsulates the above dynamic proxy code
AOP related terms:
Target: The Target object to be proxied
Proxy: When a class is woven into AOP for enhancement, a result Proxy class is produced
Joinpoint: Intercepted methods that can be enhanced
Pointcut: The method to be enhanced, the method that is actually enhanced
Advice: Enhancement method
Aspect: Pointcut+Advice
Weaving: The process of dynamic proxy
Which proxy approach is used underneath AOP: In Spring, the choice is based on whether the target class implements the interface
Clear development:
Who is the pointcut (configuration of pointcut expressions)
Who is the notification (enhancement method in the aspect class)
Weave the pointcuts and notifications into the configuration
A quick start to XML-based AOP development
Steps:
Import AOP Related Coordinates (AspectJ)
Create target interfaces and target classes (with internal pointcuts)
Create a section class (with enhanced methods inside)
Give The creation of the target and aspect classes to Spring
Configure the weaving relationship in applicationContext.xml
test
Import AOP related coordinates
< the groupId > org. Springframework < / groupId > < artifactId > spring - the context < / artifactId > < version > 5.0.5. RELEASE < / version >Copy the code
< the groupId > org. Aspectj < / groupId > < artifactId > aspectjweaver < / artifactId > < version > 1.8.4 < / version >Copy the code
Create the target interface and target class
public interface TargetInterface {
public void save();
Copy the code
}
public class Target implements TargetInterface {
public void save() { System.out.println("save running...." ); }Copy the code
}
Create a section class (with enhanced methods inside)
Give The creation of the target and aspect objects to Spring
Configure the weaving relationship in applicationContext.xml
XML configuration AOP details
The package name of the return value type. Class name. Method name (parameter)
Note:
Modifiers can be omitted
You can use an asterisk * to represent any object except modifiers
A dot between the package name and the class name. Represents the class under the current package, two dots.. Represents the classes under the current package and its subpackages
Argument lists can be made with two dots.. Represents a list of any number of parameter types
Execution (* com.itheima. Aop.. (..) )
<aop: method=” pointcut=” />
Extraction of pointcut expressions When multiple pointcut expressions are the same, configure the pointcut-ref attribute to extract pointcut expressions
<aop:before method=”before” pointcut-ref=”myPointcut”/>
Annotation based AOP configuration
Configuration syntax for notifications: @ Notification annotations (” pointcut expressions “)
Steps:
Lead up: Hand the aspect and target classes to Spring with @Component and enable Component scanning
Annotate the Aspect class with @aspect
Annotate notification methods with the @ enhanced type annotation
Configure the AOP automatic proxy in the configuration file AOP: AspectJ-AutoProxy
Give Object creation of the target and aspect classes to Spring (using annotations)
Configure the weave relationship using annotations in the aspect class
Enable component scanning and AOP automatic proxying in the configuration file
<context:component-scan base-package=”com.itheima.anno”/>
aop:aspectj-autoproxy/
test
Decoupling: Extraction of tangential expression in a section class
Spring JdbcTemplate is basically used
To import spring-JDBC and Spring-TX coordinate dependencies
Create the jdbcTemplate object template using the Spring configuration
applicationContext.xml
jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root
JdbcTemplate is a common method
int row = update(sql, … Args) is commonly used in add delete update operations to return the number of rows affected
List List = query(SQL, new BeanRowMapper()) is used to query multiple records and return a List
Object O = queryForObject(SQL, new BeanRowMapper()) is often used to query a single row and return a specified Object
Long count = queryForObject(SQL, long.class)
Spring transaction control
Programmatic transaction control
The three object
PlatformTransactionManager: platform transaction management interface
The implementation is based on the technology of different Dao layers. Different platform transaction managers encapsulate the way to control transactions, and the API is different (need to be specified through configuration).
TransactionDefinition: a TransactionDefinition object that encapsulates some of the transaction’s parameters
Isolation level, propagation behavior (need to be specified by configuration)
TransactionStatus: TransactionStatus
As the event progresses, internal information changes accordingly (no configuration is required to change).
Declarative transaction control
Function: Non-intrusive development components, similar to AOP ideas, by configuring transaction control at the system level to control the business logic, so that business logic and transaction control separate, reduce coupling, when changing transactions, only need to change in the configuration file.
AOP is at the bottom of declarative transaction control in Spring
Declarative transaction control based on XML
Steps:
Configure the dataSource and jdbcTemplate, As well as AccountDaoImpl and AccountServiceImpl
Configure the platform transaction manager (depends on the dataSource)
Configuration enhancements (specifying the transaction manager, specifying transaction properties of each transaction-controlled method such as isolation level, propagation behavior, etc.)
Configuration weaving (use AOP: Advisor, since transaction control has only one enhancement)
Annotation-based declarative transaction control
Steps:
Pre-steps: Configure AccountDaoImpl and AccountServiceImpl with annotations
Using @Transactional instead of configuration-enhanced XM configurations can be defined either ona class (which controls all methods in the class) or ona method, using the nearest principle
applicationContext.xml
AccountServiceImpl
Note: When using annotation configuration, remember to configure transaction annotation driver: TX :annotation-driven
summary
The use of Spring transaction control is mainly to use AOP ideas, do not invade the development of components, by configuring transaction control in the system level to control business logic, business logic and transaction control separate, reduce coupling
Well, that’s all for today’s article, hoping to help those of you who are confused in front of the screen