1, Understand the basic introduction and main ideas of Spring IoC/DI
1. Understand the basic introduction of Spring
(1) What is spring?
Spring is an open source framework for lightweight DI/IoC and AOP containers. It is committed to building lightweight Java EE applications and simplifying application development. It covers traditional application development and extends to mobile terminal, big data and other fields.
(2) What are the advantages of spring? And function?
① Spring can help us create and assemble dependencies between objects according to configuration files with low intrusion / low coupling.
② Spring aspect oriented programming can help us realize logging, performance statistics, security control and so on.
③ Spring can provide very simple and powerful declarative transaction management (complete the transaction through configuration without modifying the code).
④ Spring provides seamless integration with third-party data access frameworks (such as Hibernate and JPA), and it also provides a set of JDBC templates to facilitate database access.
⑤ Spring provides seamless integration with third-party Web (such as struts 1 / 2 and JSF) frameworks, and it also provides a set of Spring MVC framework to facilitate the construction of web layer.
⑥ Spring can easily integrate with technologies such as Java Mail, task scheduling and caching framework to reduce the difficulty of development.
2. Main idea IoC/DI
✿ Spring is a di container or IoC container (DI and IoC have similar ideas). Take control of the dependencies between creating objects and building objects.
● IoC: Inversion of Control:
A design idea. Its original intention is to hand over the control of manually creating objects in the program to the Spring framework.
● DI: Dependency Injection:
A design idea. Specifically, in the process of creating an object, Spring sets the object dependent properties (constants, objects, collections) to the object through configuration.
2, Master the basic use of Spring, the way Spring obtains bean objects, and the introduction and configuration of Spring tag import
1. Master the basic use of Spring
(1) Dependent jar package:
- spring-beans.jar
- spring-core.jar
- commons-logging.jar
(2) Configuration:
-
Create ApplicationContext XML configuration file:
-
Configured constraint content:
<!-- Configured bean Constraint content --> <?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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- Via configured bean Element, tell Spring of IoC Container, which class objects need to be managed --> <bean id="hello" class="com.shan.hello.Hello"> <!-- adopt property Child element, which sets the value of the attribute of the management object --> <property name="password" value="123"/> <property name="username" value="shan"/> </bean> </beans>
(3) Use:
@Test void testIoC() throws Exception { Hello hello = null; //========================= //1. Load configuration file: find the configuration file from the classpath path path and create a resource object Resource resource = new ClassPathResource("applicationContext.xml"); //2. Object creation of IoC factory (IoC object creation of spring) BeanFactory factory = new XmlBeanFactory(resource); //3. Get object from Ioc container: get object with specified name from spring IoC container (i.e. factory object) hello = (Hello)factory.getBean("hello"); //========================= hello.printUser(); }
■ from the example, we can see that spring not only helps us create objects, but also helps us set the data needed by objects (the attribute dependency of objects)
2. How Spring gets bean objects
-
Recommended: bean name + type: T getBean(String name, Class requiredType) is obtained according to the name + type of the bean object in the container
@Test void testIoC() throws Exception { Hello hello = null; //========================= //1. Load configuration file: find the configuration file from the classpath path path and create a resource object Resource resource = new ClassPathResource("applicationContext.xml"); //2. Create IoC container: create spring's factory object (IoC container object) BeanFactory factory = new XmlBeanFactory(resource); //3. Get object from Ioc container: get object with specified name from spring IoC container (i.e. factory object) //Method (recommended): t getBean (string name, class < T > requiredtype) is obtained according to the name + type of the bean object in the container hello = factory.getBean("hello", Hello.class); //========================= hello.printUser(); }
3. import configuration of Spring tag
- Element: < import resource = "COM / Shan / Hello. XML" / > the configuration file used to import spring, which is equivalent to the element < JavaScript SRC = "" / > in js
- The recommended resource path is prefixed with classpath
- By default, resource is found from the following path of classpath, for example: < import resource = "classpath: COM / Shan / Hello. XML" / >
3, Spring core objects BeanFactory and bean, spring configuration mode, and understand the principle of spring management bean
1. Spring core objects BeanFactory and Bean
-
BeanFactory: it is Spring's IoC container (container - manage the life cycle of objects). It is the factory that produces bean objects and is responsible for configuring, creating and managing beans.
-
bean: objects managed by the Spring IoC container are called beans.
2. Spring configuration
■ there are three ways to configure metadata:
□ XML based configuration
□ annotation based configuration
□ Java based configuration
3. Understand the principle of Spring managed bean s
-
The bottom layer is: reflection (get constructor instance object) + introspection mechanism (set attribute value)
① Load the configuration file through the Resource object
② Parse the configuration file to get the bean with the specified name
③ Resolve the bean element, take the id as the name of the bean, and use the class to reflect the instance of the bean
- Note: at this time, the bean class must have a parameterless constructor (and the parameterless constructor has nothing to do with access rights);
④ When calling the getBean method, return the object instance from the container;
■ conclusion: the code is transferred from JAVA file to XML.
4, Using Spring's testing framework
★ compared with the traditional testing method, the spring testing framework will help us close the object resources, while the traditional method will not normally close the spring container.
1. Dependent jar package:
- spring-test.jar
- spring-context.jar
- spring-aop.jar
- spring-expression.jar
2. Profile:
■ SpringTestTest5-context.xml file (the file name must be test class context, because it needs to correspond to the test class name):
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- to configure bean object --> <bean id="someBean" class="com.shan.spring_test.SomeBean"/> </beans>
3. Test class:
■ springtest5 class:
//SpringTest case test //Run spring JUnit 5 @SpringJUnitConfig public class SpringTestTest5 { //Indicates to automatically find the bean object in the Spring container according to the type and set it to this field @Autowired private SomeBean bean; @Test void testIoC() throws Exception { bean.doWork(); } }
5, Spring's core IoC (based on xml)
1. The difference between ApplicationContext and BeanFactory creating objects
-
When BeanFactory creates a Spring container, it does not immediately create the bean object managed in the container. It needs to wait until it obtains a bean to create it -- delaying initialization. (lazy loading)
-
ApplicationContext will create all bean s when the Spring container is started (Application is used in Web Applications)
2. Common methods of instantiating beans and implementing FactoryBean interface instantiation
(1) How to instantiate bean s:
-
Constructor instantiation (whether there is a parameter constructor in the bean), standard and commonly used.
<!-- to configure bean object --> <bean id="someBean" class="com.shan.spring_test.SomeBean"/>
(2) How to implement the instantiation of FactoryBean interface:
-
Class to implement the FactoryBean interface:
public class DogFactory implements FactoryBean<Dog>{ @Override public Dog getObject() throws Exception { Dog dog = new Dog(); return dog; } @Override public Class<?> getObjectType() { return Dog.class; } }
<!-- realization FactoryBean Interface instantiation: instance factory variant, Such as integration MyBatis Frame use --> <bean id="dog" class="com.shan._04_factory_bean.DogFactory"/>
3. bean scope, initialize init method and destroy method
(1) bean scope
- The default and common case is singleton
<bean id="" class="" scope="Scope"/>
-
Singleton: singleton (default scope) prototype: multiple instances
-
In web Applications (request, session, application)
-
globalSession: generally used in the portlet application environment. The distributed system has the concept of global session (single sign on)
-
Websocket: define a bean definition into the life cycle of websocket
(2) bean initialization and destruction:
- Attribute init method = "initialization method name in this class" and attribute destroy method = "destroy method name in this class"
- If you do not use spring's testing framework, you cannot normally close the IoC container, that is, destroy the bean object (you can close it manually)
<bean id="cat" class="com.shan.lifecycle.Cat" init-method="init" destroy-method="close"/>
6, Spring's core DI (xml based):
\({\ color{Violet} {● DI is similar to IoC. The detail is that DI is also responsible for managing the properties of bean objects} \)
1. xml configuration injection attribute value:
★ configuration and injection:
-
Constant type configuration value --- > injection setter method
-
Object type configuration ref --- > inject setter method
-
Set type configures the elements corresponding to each set... --- > Inject setter method
1. Configure assembly via XML
(1) XML auto assembly (not recommended) auto assembly through the attribute autowire of bean element
✿ (2) setter injection [attribute injection (distinguished by type)]
■ (common) inject constant value
<bean id="person" class="com.shan.di_setter.Person"> <property name="name" value="shan"/> <property name="age" value="22"/> <property name="salary" value="10000"/> </bean>
■ (common) injection object ref
<bean id="cat" class="com.shan.di_setter2.Cat"> <property name="name" value="kity"/> </bean> <bean id="person" class="com.shan.di_setter2.Person"> <property name="name" value="shan"/> <property name="age" value="22"/> <property name="cat" ref="cat"/> </bean>
■ injection set
<bean id="person" class="com.shan.di_setter3.Person"> <!-- set type --> <property name="set"> <set> <value>set1</value> <value>set2</value> </set> </property> <!-- list type --> <property name="list"> <list> <value>list1</value> </list> </property> <!-- array type --> <property name="array"> <array> <value>array1</value> </array> </property> <!-- map Type (Dictionary type) --> <property name="map"> <map> <entry key="key1" value="value1"/> </map> </property> <!-- properties Type (special) map Type[ key and value All strings]) --> <property name="prop"> <value> p1=v1 p2=v2 </value> </property> </bean>
2. bean element inheritance (essentially a copy of xml configuration content)
-
Extract through abstract attribute
-
Import through parent attribute
3. Attribute injection application - configure database connection pool
-
Dynamically load the configuration file (db.properties - configuration information of database connection)
-
<context:property-placeholder/>
-
Use ${} to dynamically import attribute values
(1) Configure database connection pool
<!-- Configure database connection pool --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/springdemo?useSSL=false"/> <property name="username" value="root"/> <property name="password" value="admin"/> <property name="initialSize" value="2"/> </bean>
(2) db.properties ---- configuration information of database connection
(3) property place holder
● if the label Context is used, the constraint of the Context needs to be introduced first (it can be modified on the basis of beans):
● context: Property placeholder
<!-- from classpath Root path loading db.properties --> <context:property-placeholder location="classpath:db.properties"/>
● use ${} to dynamically introduce attribute values
<!-- Configure database connection pool --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="initialSize" value="${jdbc.initialSize}"/> </bean>
7, Spring uses annotation configuration
1. Three elements of annotation: annotation itself, pasted and third-party program (special functions given to annotation)
★ for IoC annotation and DI annotation: their third-party program is their corresponding parser.
-
IoC annotation: component scanner < context: component scan base package = "" / >
-
DI annotation: annotation configuration < context: annotation config / >
2. DI comments: @ Autowired, @ Resource, @ Value
- Power of value annotation: introduce value variables in combination with dynamic properties configuration file, for example: @ Value("${service.port}")
(1) Inject attribute values through annotations
★ configuration and injection:
-
Constant type configuration Value - > inject @ Value
-
Object type configuration ref - > inject @ Autowired/@Resource
(2) IoC comments: @ Component, @ Scope, @ PostConstruct, @ PreDestroy
★ use annotation @ Component (configure Bean)
//Equivalent to < bean id = "datasource" class = "com. Shan. IOC. Mydatasource" / > @Component("dataSource") public class MyDataSource { }
★ bean component version:
@Component refers to a component in general
@Repository persistence layer
@Service business layer
@Controller control layer
★ Scope annotation, initialization and destruction annotation: @ Scope, @ PostConstruct, @ PreDestroy
\({\ color{Violet} {■ where annotations are initialized and destroyed [dependency: javax. Annotation API. Jar]} \)
8, Spring AOP
1. Understand the idea of AOP [the idea of aspect oriented programming] and the principle of AOP
(1) The idea of Aspect Oriented Programming:
Using a technology called "crosscutting", the interior of the encapsulated object is cut open, and the public behaviors that affect multiple classes are encapsulated into a reusable module, which is named "Aspect", that is, facet.
-
Section: put the crosscutting concerns one by one into a module, which is called section.
-
Then each aspect can affect a certain function of the business. The purpose of the aspect is function enhancement,
For example, the log section is a crosscutting concern. If many methods in the application need to log, they only need to insert the log section
(2) Principle of AOP thought: dynamic agent
2. Pointcot syntax
- Find a specific method -- which package Which class Which method
Execution (< modifier >? < return type > < declaration type >? < method name > (< parameter >) < exception >)
-
Wildcard in pointcut expression (see the specific method, starting with the method name):
*: matches any part, but represents only one word.
..: can be used in fully qualified names and method parameters, representing subpackages and 0 to N parameters respectively.
3. AOP development:
(1) Dependent jar package:
- spring-aop.jar
- com. springsource. org. aopalliance. Jar [spring-aop.jar of spring5 has been included]
- com.springsource.org.aspectj.weaver.jar
(2) Configuration:
-
Constraints for introducing AOP:
-
3W what, where and when of AOP
<!-- AOP Configuration: where, when and what to do --> <!-- 1,what: What to enhance --> <bean id="transactionManager" class="com.shan.tx.TransactionManager"/> <aop:config proxy-target-class="false"> <!-- attribute proxy-target-class Configure whether to use real objects --> <!-- to configure AOP section --> <aop:aspect ref="transactionManager"> <!-- relation what --> <!-- 2,where: Enhance on which methods in which classes in which packages --> <aop:pointcut id="txPoint" expression="execution(* com.shan.service..*Service*.*(..))"/> <!-- 3,when: When to enhance the method execution --><!-- relation where --> <aop:before method="open" pointcut-ref="txPoint"/> <aop:after-returning method="commit" pointcut-ref="txPoint"/> <aop:after-throwing method="rollback" pointcut-ref="txPoint"/> <aop:after method="close" pointcut-ref="txPoint"/> <aop:around method="aroundMethod" pointcut-ref="txPoint"/> </aop:aspect> </aop:config>
4. AOP enhanced classification
■ according to the execution time of the enhanced method, it is divided into: pre enhancement, post enhancement, abnormal enhancement, final enhancement and surround enhancement
- Pre enhancement: permission control, logging, etc. [before the enhanced method is executed]
- Post enhancement: submit transactions, statistical analysis data results, etc. [after the enhanced method is executed normally (there is no exception halfway)]
- Final enhancement: rollback transaction, record log exception information, etc. [exception occurs in the enhanced method]
- Final enhancement: release resources, etc. [finally]
- Surround enhancement: caching, performance logging, permissions, transaction management, etc. [you can customize when the enhanced method is executed (return an Object, parameter processingjoinpoint)]
5. Get the information of the enhanced method and pass it to the enhanced method [parameter Joinpoint class]
-
Joinpoint class is a connection point to access the real object, proxy object, method parameters, etc. of the enhanced method
-
The first parameter can be used as a parameter of pre -, post -, exception -, and final enhancement methods
//It can be used as parameters of pre -, post -, exception - and final enhancement methods, * * ` the first parameter`** public void open(JoinPoint jp) { System.out.println("Open transaction~"); System.out.println("Proxy object:" +jp.getThis().getClass()); System.out.println("Target object:" +jp.getTarget().getClass()); System.out.println("Parameters of the enhanced method:" +Arrays.toString(jp.getArgs())); System.out.println("Signature of connection point method:" +jp.getSignature()); System.out.println("Type of current connection point:" +jp.getKind()); }
5-2. Call the method of real object around the enhanced method [parameter processingjoinpoint]
-
Parameter processingjoinpoint: it is a subclass of jointpoint and can only be used for surround enhancement as the first parameter
You can also call enhanced methods in real objects.
//Call the method of real object RET = PJP proceed(); public Object aroundMethod(ProceedingJoinPoint pjp) { Object ret = null; System.out.println("Open transaction~"); try { ret = pjp.proceed();//Calling methods of real objects System.out.println("Calling methods of real objects...~"); System.out.println("Commit transaction~"); } catch (Throwable e) { System.out.println("Rollback transaction~,error message:" + e.getMessage()); }finally { System.out.println("close resource~"); } return ret; }
6. Configuring AOP with annotations
(1) Parser for AOP annotation [Third Party program, special functions for annotation]:
- Use cglib annotation: configure attribute proxy target class = "true"
<!-- what --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- AOP Annotated parser --> <aop:aspectj-autoproxy/>
(2) Use annotation @ Aspect (configure an AOP Aspect)
- @Pointcut (configure where)
- @Before, @ AfterReturning, @ AfterThrowing, @ After, @ Around (when configured)
@Component@Aspect //Configure an AOP section public class TransactionManager { //where //xml:<aop:pointcut id="txPoint" expression="execution(* com.shan.service..*Service*.*(..))"/> @Pointcut("execution(* com.shan.service..*Service*.*(..))") public void txPoint() { } //@Before("txPoint()") public void open(JoinPoint jp) { System.out.println("Open transaction~"); } //@AfterReturning("txPoint()") public void commit() { System.out.println("Commit transaction~"); } //@AfterThrowing(value="txPoint()", throwing="ex") public void rollback(Throwable ex) { System.out.println("Rollback transaction~,Exception information:" +ex.getMessage()); } //@After("txPoint()") public void close() { System.out.println("close resource~"); } @Around("txPoint()") public Object aroundMethod(ProceedingJoinPoint pjp) { Object ret = null; System.out.println("Open transaction~"); try { ret = pjp.proceed();//Calling methods of real objects System.out.println("Calling methods of real objects...~"); System.out.println("Commit transaction~"); } catch (Throwable e) { System.out.println("Rollback transaction~,error message:" + e.getMessage()); }finally { System.out.println("close resource~"); } return ret; } }
9, Spring DAO
1. Template class and base class:
2. pring JDBC [JDBC template template class]
(1) Dependent jar package:
- mysql-connector-java.jar [you can also use the Druid connection pool: druid.jar]
- spring-jdbc.jar
- spring-tx.jar
(2) Summary JdbcTemplate template class - handling CRUD operations
//DML operation: public update(String sql, Object...args) Parameters: sql ?Parameter corresponding to placeholder Return: number of rows affected //DQL operation: public <T>List<T> query(String sql, Object...args, RowMapper<T> rowMapper) Parameters: sql ?Parameter corresponding to placeholder Result set processor Return: multi row result set encapsulated list
3. Problems and solutions of template class JdbcTemplate NameParameterJdbcTemplate
(1) Question:
● placeholders used in the template class JdbcTemplate? [sequence placeholder], the number you need to count, and then write the corresponding parameters. The parameters are too troublesome
● select * from employee where id in
- I don't know how to write after in. Should I write one? Or (how many? All uncertain)
(2) Solution: use NameParameterJdbcTemplate
-
The named parameter JdbcTemplate template is actually a layer outside the JdbcTemplate.
-
It is allowed to use xx to name the placeholder parameter. We need to set the parameter for the position with the name XX.
□ example:
public int countOfActorsByFirstName(String firstName) { String sql = "select count(*) from T_ACTOR where first_name = :first_name"; Map<String, String> namedParameters = Collections.singletonMap("first_name", firstName); return this.namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Integer.class); }
10, Spring ORM -- integrated mybatis framework
11, Spring tx
1. Spring's transaction management mainly includes three APIs:
- PlatformTransactionManager: create a transaction according to the transaction attribute configuration information provided by TransactionDefinition.
- Transaction definition: encapsulates transaction isolation level and timeout, whether it is read-only transaction, isolation level of transaction, propagation rules and other transaction attributes
- TransactionStatus: encapsulates the specific running status of the transaction. If the transaction is newly opened or has been committed, set the current transaction as rollback only
✿ note: common transaction managers:
-
JDBC/MyBatis: DataSourceTransactionManager
-
Hibernate: HibernateTransactionManager
2. Transaction propagation rule TransactionDefinition and common cases
(1) Transaction propagation rules:
In a transaction method, the method of other transactions is invoked, and how the transaction is transmitted and what rules are propagated.
(2) Common situations:
■ situation 1: need to respect / comply with current affairs
- REQUIRED: (common) there must be a transaction. If there is a transaction currently, it will be added to the transaction. Otherwise, a new transaction will be created
■ case 2: failure to comply with the current transaction
- Requirements NEW: (common) a NEW transaction will be opened no matter whether there is a transaction or not It must be a NEW transaction
■ case 3: parasitic transaction (external transaction / internal transaction / nested transaction)
- NESTED: parasitic transaction. If there is a current transaction, it will be executed within the internal transaction If no transaction currently exists, a new transaction is created
3. Transaction configuration (based on xml and annotations)
(1) Based on xml: transaction enhancement - the essence is AOP enhancement what, when and where
<!-- ===============Like AOP,Transaction enhancement================================== --> <!-- 1,what: to configure jdbc Transaction manager --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 2: when: Configure transaction manager enhancements(Surround enhancement) --><!-- relation what --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="trans"/> </tx:attributes> </tx:advice> <!-- 3,where: Configuration section --><!-- relation when --> <aop:config> <aop:pointcut id="txPc" expression="execution(* com.shan.service.*Service.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc"/> </aop:config>
(2) Configuring jdbc transactions with annotations: tx annotation parser, @ Transactional
-
Comment: @ Transactional
-
Annotation attributes: name, propagation, isolation, timeout, read only, rollback for, no rollback for
■ annotation third party analysis:
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- tx Annotation parser --> <tx:annotation-driven transaction-manager="txManager"/>
■ annotation @ Transactional use:
@Service@Transactional public class AccountServiceImpl implements IAccountService{ @Autowired private IAccountDAO dao; @Override public void trans(Long outId, Long inId, int money) { dao.transOut(outId, money); int a = 1/0; //Arithmetic anomaly dao.transIn(inId, money); } //If there is a query method, you can add annotation attribute to @ Transactional @Transactional(readOnly = true) public void listXX() { } }
(3) Transaction configuration (based on annotation + Java Config configuration)
-
Notes:
\({\ color{Blue}{@Configuration} \) configuration
\({\ color {blue} {@ import (configuration subclass)} \)
\({\ color{Blue}{@Bean} \) configure to create a bean object
\({\ color {blue} {@ componentscan} \) IOC annotation parser
\({\ color{Blue}{@EnableTransactionManagement} \) transaction annotation parser
@Transactional configuring jdbc transactions
@PropertySource configures the imported property file resource
\({\ color{Gray}{@Component} \) refers to components in general
\({\ color{Gray}{@Repository} \) persistence layer
\({\ color{Gray}{@Service} \) business layer
\({\ color{Gray}{@Controller} \) control layer
@Value configures the injection property value
@Autowired configuration injection attribute value