What is Spring
Spring is a lightweight open source framework for layered Java SE/EE application full stack, with IOC (inversion control) and AOP (aspect oriented programming) as the kernel
configuration file
Name: whatever, but don't have Chinese
Location: whatever
<?xml version="1.0" encoding="UTF-8"?> <!-- Import constraints spring-framework-4.2.4.RELEASE/docs/spring-framework-reference/html/xsd-configuration.html --> <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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- create object --> <bean id="customerService" class="com.leiyuee.service.impl.CustomerServiceImpl"></bean> <bean id="customerDao" class="com.leiyuee.dao.impl.CustomerDaoImpl"></bean> </beans>
Writing test classes
public class Client { /** * Spring Getting started with IOC * * Spring Container interface: * ApplicationContext * * His implementation class: * ClassPathXmlApplicationContext: Parses the xml file under the classpath * FileSystemXmlApplicationContext: An xml file was found anywhere on the system disk */ public static void main(String[] args) { //Build a factory based on the configuration file ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); //Get bean by id ICustomerService cs = (ICustomerService) ac.getBean("customerService"); ICustomerDao cd = (ICustomerDao) ac.getBean("customerDao"); //Output memory address System.out.println(cs); System.out.println(cd); } }
1, IoC
IoC (Inversion of Control): control inversion. The creation of instances is managed by spring. The creation of objects is not created by new operation in the code, but by spring configuration.
DI (Dependency Injection): Dependency Injection. When spring manages a class, it will inject the dependent attributes of the class, that is, the attribute values in the injected class
Underlying principle: factory design pattern + reflection + XML configuration file
public class Client { /** * Spring Getting started with IOC * * Spring Container interface: * ApplicationContext: All objects configured in the container are created when the container is started * * His implementation class: * ClassPathXmlApplicationContext: Parses the xml file under the classpath [recommended] * FileSystemXmlApplicationContext: An xml file was found anywhere on the system disk * * Early API s: * Interface: BeanFactory: the object will be created every time the object is obtained * Implementation class: XmlBeanFactory * * The difference between the early api and the current api: * Early APIs: use of deferred loading strategy * Today's api: using the immediate load strategy * * Mainly due to the development of IT technology and the popularity of memory * * Methods of obtaining bean s from these APIs: * getBean(); * The parameter of this method is the id of the bean in the container [that is, the value of the id attribute corresponding to the bean tag] */ @SuppressWarnings("all") public static void main(String[] args) { //Build a factory based on the configuration file //Read configuration file under classpath // ApplicationContext ac = new ClassPathXmlApplicationContext("/com/leiyuee/ui/bean.xml"); ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); //Read configuration file from file system // ApplicationContext ac = new FileSystemXmlApplicationContext("src/bean.xml");// Relative path // ApplicationContext ac = new FileSystemXmlApplicationContext("C:\workspace\SpringIOC_BeanFactory\src\bean.xml");// Absolute path //Early API // Resource res = new ClassPathResource("bean.xml"); // BeanFactory ac = new XmlBeanFactory(res); //Get bean by id ICustomerService cs = (ICustomerService) ac.getBean("customerService"); ICustomerDao cd = (ICustomerDao) ac.getBean("customerDao"); //Output memory address System.out.println(cs); System.out.println(cd); } }
Spring configuration file interpretation
<?xml version="1.0" encoding="UTF-8"?> <!-- Import constraints spring-framework-4.2.4.RELEASE/docs/spring-framework-reference/html/xsd-configuration.html --> <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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- create object --> <!-- bean Tag: configure the object to be managed, that is bean Properties: id: yes bean The unique identification of the container cannot be repeated class: The fully qualified name of the class, the object created by the framework through reflection technology, and the object is created by calling the parameterless construction method by default scope: Scope of class singleton : Single example [default value] : Service and Dao All use a single example prototype : Multiple cases : Action Use multiple cases request: Request one instance at a time [understand] session: One session and one instance [understand] init-method: Initialization method destroy-method : Method of destruction bean Life cycle of: singleton : Single case 1)When was he born : The container is created and it is born 2)When will you live : The container is here. It's there 3)When did you die : If the container is destroyed, it will die prototype : Multiple cases 1)When was he born : call getBean When I was born 2)When to live: live as long as there is a quote 3)When to die: there are no references waiting to be collected by the garbage collection mechanism --> <bean id="customerService" class="com.leiyuee.service.impl.CustomerServiceImpl" scope="prototype" init-method="init" destroy-method="des" ></bean> <bean id="customerDao" class="com.leiyuee.dao.impl.CustomerDaoImpl"></bean> </beans>
1. Dependency injection
1.1 construction method
<?xml version="1.0" encoding="UTF-8"?> <!-- Import constraints spring-framework-4.2.4.RELEASE/docs/spring-framework-reference/html/xsd-configuration.html --> <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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="customerService" class="com.leiyuee.service.impl.CustomerServiceImpl" scope="prototype" init-method="init" destroy-method="des" ></bean> <bean id="customerDao" class="com.leiyuee.dao.impl.CustomerDaoImpl"></bean> </beans>
1.2 set method injection
1) Provide a set method to the global attribute
public class CustomerServiceImpl implements ICustomerService { //set method injection private String name; private Integer age; private Date birthday; public void setName2(String name) { this.name = name; } public void setAge(Integer age) { this.age = age; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public void saveCustomer() { System.out.println(name); System.out.println(age); System.out.println(birthday); } }
2) Use the property tag in the configuration file
<?xml version="1.0" encoding="UTF-8"?> <!-- Import constraints spring-framework-4.2.4.RELEASE/docs/spring-framework-reference/html/xsd-configuration.html --> <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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- create object --> <bean id="customerService" class="com.leiyuee.service.impl.CustomerServiceImpl" > <!-- 1) Injection by construction method: Understanding constructor-arg Tag injection attribute: there are several tags with several parameters Properties: index: Index of the parameter of the constructor, starting from 0 name : Parameter name of construction method [this is enough] type : The data type of the parameter of the constructor ===============Where is the assignment above===What values are assigned below value: Inject basic data types and String ref: other bean Type, other bean of id <constructor-arg name="name2" value="Wolverine" /> <constructor-arg name="age" value="300" /> <constructor-arg name="birthday" ref="now"/> 2)adopt set Method injection: top priority property label:adopt set Method injection, find set The string following the method, starting with lowercase Properties: name: Yes set The string following the method, starting with lowercase value: Inject basic data types and String ref: other bean Type, other bean of id --> <constructor-arg name="name2" value="Wolverine" /> <constructor-arg name="age" value="300" /> <constructor-arg name="birthday" ref="now"/> <property name="name2" value="Little duck"></property> <property name="age" value="20"></property> <property name="birthday" ref="now"></property> </bean> <bean id="now" class="java.util.Date"></bean> </beans>
1.3 injection of complex data types
<?xml version="1.0" encoding="UTF-8"?> <!-- Import constraints spring-framework-4.2.4.RELEASE/docs/spring-framework-reference/html/xsd-configuration.html --> <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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="customerService" class="com.leiyuee.service.impl.CustomerServiceImpl" > <!-- 1) Injection by construction method: Understanding constructor-arg Tag injection attribute: there are several tags with several parameters Properties: index: Index of the parameter of the constructor, starting from 0 name : Parameter name of construction method [this is enough] type : The data type of the parameter of the constructor ===============Where is the assignment above===What values are assigned below value: Inject basic data types and String ref: other bean Type, other bean of id <constructor-arg name="name2" value="Wolverine" /> <constructor-arg name="age" value="300" /> <constructor-arg name="birthday" ref="now"/> 2)adopt set Method injection: top priority property label:adopt set Method injection, find set The string following the method, starting with lowercase Properties: name: Yes set Method, the first letter of which is lowercase value: Inject basic data types and String ref: other bean Type, other bean of id 3)Inject complex data types It's also used property Tag, use whatever type it is The data structure is the same, and the labels can be interchanged: list and map That's enough --> <property name="myArray" > <set> <value>eee</value> <value>fff</value> </set> </property> <property name="myList"> <array> <value>aaa</value> <value>bbb</value> </array> </property> <property name="mySet"> <list> <value>ccc</value> <value>ddd</value> </list> </property> <property name="myMap"> <props> <prop key="a1" >iii</prop> <prop key="a2" >jjj</prop> </props> </property> <property name="myProp"> <map> <entry key="k1" value="ggg"></entry> <entry key="k2" value="hhh"></entry> </map> </property> </bean> </beans>
2. Annotation
Guide Package
Create an XML file with any name under the root path of the class (cannot be Chinese -- bean XML)
Use @ Component annotation to configure managed resources
/** * <!-- Create object -- > <bean id="customerService" class="com.leiyuee.service.impl.CustomerServiceImpl"> <property name="customerDao" ref="customerDao"></property> </bean> * ==================================== * 1,Creating annotations for objects * @Component : Component means that it is used to create objects and put the current object into the Spring container * 1)If there are no other attributes, the id is a short class name with a lowercase initial * Writing this component on a class is equivalent to handing over the class to Spring for management */ @Component // Equivalent to: < bean id = "customerserviceimpl" class = "com. Leiyuee. Service. Impl. Customerserviceimpl" / > public class CustomerServiceImpl implements ICustomerService { private ICustomerDao customerDao; public void setCustomerDao(ICustomerDao customerDao) { this.customerDao = customerDao; } @Override public void saveCustomer() { customerDao.save(); } }
Write a configuration file and tell Spring to scan the package of the component
<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- tell Spring Where is our creation object annotation 1)Import a context Namespace for 2)Enable the scan of the created object annotation [component] context:component-scan Properties: base-package : Write the base package to be scanned, referred to as the base package --> <context:component-scan base-package="com.leiyuee"></context:component-scan> </beans>
2.1 common notes
/** * <!-- Create object -- > <bean id="customerService" class="com.leiyuee.service.impl.CustomerServiceImpl"> <property name="customerDao" ref="customerDao"></property> </bean> * * ==================================== * 1,Creating annotations for objects * @Component : Component means that it is used to create objects and put the current object into the Spring container * 1)If there is no value attribute, the id is a short class name with a lowercase initial * Writing this component on a class is equivalent to handing over the class to Spring for management * For example: @ Component * // Equivalent to: < bean id = "customerserviceimpl" class = "com. Leiyuee. Service. Impl. Customerserviceimpl" / > * 2)If there is a value attribute, id is the value of value * For example: @ Component(value="customerService") | @ Component("customerService") * // Equivalent to: < bean id = "customerservice" class = "com. Leiyuee. Service. Impl. Customerserviceimpl" / > * ------------------------------------------------ * @Component The three annotations derived from annotations are derived for the three-tier architecture * web Layer: @ Controller * service Layer: @ Service * dao Layer: @ Repository * * The three annotations as like Component annotations are as like as two peas. * * 2,Spring Scope of objects in containers: single instance and multi instance problems * <bean id="customerServiceImpl" * class="com.leiyuee.service.impl.CustomerServiceImpl" * scope="singleton[Default] |prototype|request|session "/ > * @Scope : Specify the scope of the object, that is, single or multiple instances, which is consistent with the scope attribute in the bean tag * Properties: * value: Specify single instance or multiple instances * singleton: Single case * prototype: Multiple cases * * ------------------------------------------------------- * 3,Annotation of dependency injection: * @Autowired [Recommendation]: automatic injection with type. If this annotation is used, the set method is not necessary * 1)When there is only one object in the container, it is automatically injected * 2)When there are multiple objects in the container, take the name of the attribute as the key to find the object injection in the Spring container * Inject if you can find it * If you can't find it, you'll get rotten slag [abnormal throwing] * * @Qualifier : * 1)Used on the basis of Autowired, its value attribute specifies the id of the bean in the container * 2)If it is used on method parameters, it can be used separately, * * @Resource [[recommended]: * 1)If you don't write any attributes, it works the same as @ Autowired # * 2)If there are multiple beans in a container, you need to specify the id of the bean and use the name attribute * * @Value : Inject other data types: basic data type and String * Spring EL expressions can be used in it. I'll talk about it later */ //@Component / / equivalent to: < bean id = "customerserviceimpl" class = "com. Leiyuee. Service. Impl. Customerserviceimpl" / > //@Component("customerService") / / equivalent to: < bean id = "customerservice" class = "com. Leiyuee. Service. Impl. Customerserviceimpl" / > @Service("customerService") // Equivalent to: < bean id = "customerservice" class = "com. Leiyuee. Service. Impl. Customerserviceimpl" / > //@Scope(value="singleton") @Scope("singleton") public class CustomerServiceImpl implements ICustomerService { /*@Autowired//Automatic injection according to type @Qualifier("cd2")//value The attribute of specifies the id of the bean in the container*/ @Resource(name="cd") private ICustomerDao customerService=null; @Value("Zhang San") private String name; @Value("18") private Integer age; @Override public void saveCustomer() { customerService.save(); System.out.println(name); System.out.println(age); } }
2.2 pure notes
- Configuration class
/** * @Configuration : This annotation is life. The current class is a configuration class, and spring will scan other annotations on this class * @ComponentScan : Specifies the base package for the scan * Properties: * basePackages : Specify the base package to scan * value : Specify the base package to scan */ @Configuration //@ComponentScan(basePackages={"com.leiyuee"}) //@ComponentScan(value={"com.leiyuee"}) @ComponentScan("com.leiyuee") public class SpringConfiguration { }
- Container implementation class
public static void main(String[] args) { //1. Get Spring container ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class); //2. Get Bean by id ICustomerService cs = (ICustomerService) ac.getBean("customerService"); // ICustomerService cs2 = (ICustomerService) ac.getBean("customerService"); // ICustomerDao cd = (ICustomerDao) ac.getBean("cd"); CustomerDaoImpl cd = (CustomerDaoImpl) ac.getBean("cd"); /*if(cd instanceof ICustomerDao){ System.out.println("Is this interface type: ICustomerDao "); }else{ System.out.println("Not this interface type: ICustomerDao "); }*/ //3. Testing System.out.println(cs); System.out.println(cd); cs.saveCustomer(); }
1) Bean annotation
//@Component //<bean id="jdbcConfig" class="com.leiyuee.config.JdbcConfig"/> public class JdbcConfig { /** * @Bean Note: give the return value of the method to Spring management * 1)If the name attribute is specified: the id of the bean is the value of the attribute * Definition: @ Bean(name="ds") * Get: ac.getBean("ds"); * 2)If the name attribute is not specified: the id of the bean is the method name without the following parentheses * Definition: @ Bean * Get: ac.getBean("createDs"); */ @Bean(name="ds")//<bean id="ds" class="com.mchange.v2.c3p0.ComboPooledDataSource"/> public DataSource createDs() throws Exception{ ComboPooledDataSource ds = new ComboPooledDataSource(); ds.setDriverClass("com.mysql.jdbc.Driver"); ds.setJdbcUrl("jdbc:mysql://localhost:3306/test"); ds.setUser("root"); ds.setPassword("root"); return ds; } }
2) Import annotation
/** * @Configuration : This annotation is life. The current class is a configuration class, and spring will scan other annotations on this class * @ComponentScan : Specifies the base package for the scan * Properties: * basePackages : Specify the base package to scan * value : Specify the base package to scan * * @Import : Import other configuration classes * There is only one value attribute, which specifies the bytecode object of the configuration class */ @Configuration //@ComponentScan(basePackages={"com.leiyuee"}) //@ComponentScan(value={"com.leiyuee"}) @ComponentScan("com.leiyuee") @Import(JdbcConfig.class) public class SpringConfiguration { }
2, AOP
Aspect Oriented Programming -- Aspect Oriented Programming
Extract the repeated code of the program, and when it needs to be executed, use the dynamic agent technology to enhance our existing methods without modifying the source code.
Functions: - during the running of the program, the existing methods are enhanced without modifying the source code
Advantages: - reduce duplicate code - improve development efficiency - maintain methods
Characteristics of dynamic agent - bytecode is created as you use and loaded as you use
Interface based dynamic agent
Provider: the official Proxy class of JDK
Requirement: the proxy class implements at least one interface
Subclass based dynamic agent
Provider: CGLib of a third party. If asmxxx exception is reported, asm.exe needs to be imported jar
Requirement: the proxied class cannot be modified with final (final class)
<?xml version="1.0" encoding="UTF-8"?> <!-- Import constraints Document not found: spring-framework-4.2.4.RELEASE/docs/spring-framework-reference/html/xsd-configuration.html --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- create object --> <bean id="customerService" class="com.leiyuee.service.impl.CustomerServiceImpl"></bean> <!-- Spring of AOP Configuration steps --> <!-- Step 1: Import aop of jar package --> <!-- Step 2: give the notification class to Spring Administration --> <bean id="myLog" class="com.leiyuee.utils.Logger"></bean> <!-- Step 3: AOP Configuration of --> <aop:config> <!-- Configure global pointcuts: aspect Outside the label --> <aop:pointcut expression="execution(* com.leiyuee.service.impl.*.*(..))" id="pt1"/> <!-- Step 4: configure section : id Attribute is the unique identification of the section; ref Attribute: reference the notification class. After referencing the notification class, the notification class becomes a faceted class--> <aop:aspect id="myAspect" ref="myLog"> <!-- aop:before : Pre notification: executed before the business method <aop:before method="beforePrintLog" pointcut-ref="pt1"/> Post notification: only when the business method is executed normally <aop:after-returning method="afterReturnningPrintLog" pointcut-ref="pt1"/> Exception notification: only when the business method has an exception can it be executed <aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"/> The most general notice: the business method will be executed no matter whether there are exceptions or not <aop:after method="afterPrintLog" pointcut-ref="pt1"/> --> <!-- For details, please refer to the notice category: Logger Medium aroundPrintLog method --> <aop:around method="aroundPrintLog" pointcut-ref="pt1"/> </aop:aspect> </aop:config> </beans>
Pointcut expression
How to write the pointcut expression:
Modifier , return type , package name Package name Class name Method name (parameter list)
Full matching method:
public void com.leiyuee.service.impl.CustomerServiceImpl.saveCustomer()
Modifier: can be omitted
void com.leiyuee.service.impl.CustomerServiceImpl.saveCustomer()
Return type: you can use the * sign instead of any return type
* com.leiyuee.service.impl.CustomerServiceImpl.saveCustomer()
Package name: a * sign can be used instead of a package
* *.*.*.*CustomerServiceImpl.saveCustomer()
Package name: you can use Represents the current package and its sub packages
* *..CustomerServiceImpl.saveCustomer()
Class name: you can use the * sign instead of any class name
* *..*.saveCustomer()
Method name: you can use the * sign instead of any method name
* *..*.*()
Parameter list: a * sign can be used instead of a parameter, excluding no parameters
* *..*.*(*)
Parameter list: you can use Represents any parameter, including no parameter
* *..*.*(..)
All pass matching method: [generally not used. If you use it, be careful and cut yourself carefully]
* *..*.*(..)
Suggested usage: only cut to a certain layer
For example: * com leiyuee. service. impl.*.* (..)
/** * This class is a notification class [aspect class] */ public class Logger { //Notification method: Front public void beforePrintLog(){ System.out.println("Pre notification: print log"); } //Notification method: Post public void afterReturnningPrintLog(){ System.out.println("Post notification: print log"); } //Notification method: exception public void afterThrowingPrintLog(){ System.out.println("Exception notification: print log"); } //Notification method: Final public void afterPrintLog(){ System.out.println("Final notification: print log"); } } //Around Advice /** * Surround notification: * This notification is special and requires us to manually execute the business method * One parameter is required: ProceedingJoinPoint * This is an interface. We don't care. spring injected it into us * * This interface has a release method: * proceed(); */ @Around("pt1()") public void aroundPrintLog(ProceedingJoinPoint pjp){ try { //Before advice System.out.println("Pre notification: log printed"); //Business layer approach pjp.proceed(); //Post notification System.out.println("Post notification: log printed"); } catch (Throwable e) { //Exception notification System.out.println("Exception notification: log printed"); e.printStackTrace(); }finally{ System.out.println("Final notification: log printed"); } }
3, Business
1. Basic characteristics
(1) Atomicity means that all operations contained in a transaction either succeed or fail to roll back. Therefore, if the transaction operation succeeds, it must be fully applied to the database. If the operation fails, it cannot have any impact on the database.
(2) Consistency consistency means that a transaction must change the database from one Consistency state to another, that is, a transaction must be in a Consistency state before and after execution.
(3) Isolation: when multiple users access the database concurrently, such as operating the same table, the transactions opened by the database for each user cannot be disturbed by the operations of other transactions, and multiple concurrent transactions should be isolated from each other.
(4) Durability refers to that once a transaction is committed, the changes to the data in the database are permanent, and the operation of submitting the transaction will not be lost even in the case of database system failure.
2. Classification of transactions in Spring
2.1 programmable transaction control
Controlling transactions manually is called programmatic transaction control.
Jdbc Code:
Conn.setAutoCommit(false); / / set manual control transactions
Hibernate Code:
Session.beginTransaction(); / / start a transaction
[fine grained transaction control: transaction control can be added to the specified method and some lines of the specified method]
(it's flexible, but it's cumbersome to develop: start, commit and rollback every time.)
2.2 declarative transaction control
Spring provides transaction management, which is called explicit transaction management.
Spring provides an implementation of transaction control. If users want to use spring's declarative transaction management, they only need to configure it in the configuration file; Remove the configuration directly when you don't want to use it. This realizes the maximum decoupling of transaction control.
The core implementation of Spring declarative transaction management is based on Aop.
[coarse grained transaction control: transactions can only be applied to the whole method, not to a few lines of the method.]
(because aop intercepts methods.)
Spring declarative transaction manager class:
Jdbc Technology: data source transaction manager
Hibernate Technology: Hibernate transaction manager
2.3 use
< TX: annotation driven / > in 1.xml file
2. Declare on the method or class to be managed
@Transactional(isolation=Isolation.REPEATABLE_READ,readOnly=false,propagation=Propagation.REQUIRED