1. Overview of the Spring Framework
1. Spring is an open source lightweight JavaEE framework.
Lightweight: Small in size, jar can be used independently without relying on other jar packages,
Open source: free, source code available
Frameworks: Address the complexity of development and simplify enterprise development.
2. Two core parts of spring: IOC, Aop
IOC: Inversion of control, hand over the process of creating objects to spring for management.
Aop: Aspect-oriented, adding or enhancing functions without modifying the source code.
3. Features of spring framework:
1), facilitate decoupling and simplify development: the relationship between objects and objects depends on spring.
2), Aop programming support: do not change the source code, enhance the function
3), easy to test;
4), it is convenient to integrate various excellent frameworks.
5), to facilitate food management and reduce the difficulty of using API
6), the classic learning example of java source code.
4. Introductory case:
1), download Spring5:
spring URL: spring.io
Direct download address: https://repo.spring.io/artifactory/plugins-release/org/springframework/spring/
Also download a log jar package, spring5 depends on this jar package commons-login this jar
Download link: commons-logging-1.1.1.jar download and Maven, Gradle import code, pom file and class in the package - Times Java (nowjava.com)
I personally download 5.2.6
2) After the download is complete, participate in a common java project and import the jar into the project
3), use spring
(1), create a common class, create a common method in the class
public class User {
public void add(){
System.out.println("add.......");
}
}
(2), create a spring configuration file, configure the created object in the configuration file
a, Spring configuration files are configured using xml files
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置User对象创建-->
<bean id = "user" class = "com.yuge.User"></bean>
</beans>
b, create a test class Test
public class Tset {
@Test
public void testAdd(){
//1.读入上下文配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
//2.获取配置对象
User user = context.getBean("user", User.class);
System.out.println(user);
user.add();
}
}
c, test the result, successfully create the object, and call the method
Second, the IOC container
1. The underlying principle of IOC
1), what is IOC:
Inversion of control, the creation of objects and the interaction between objects are handed over to spring for management.
2), the purpose of using IOC
To reduce coupling
3) IOC entry case
2. The underlying principle of IOC
1), xml parsing, factory mode, reflection
2) Graphical IOC underlying principle
Traditional way:
Factory pattern:
IOC mode:
3.IOC interface (BeanFactory)
IOC is completed based on the container, and the bottom layer of the IOC container is the object factory
1), BeanFactory interface:
The most basic implementation of the IOC container is the internal use interface of spring, and it is not recommended for developers to use it.
2), ApplicationContext interface:
It is a sub-interface of BeanFactory, which provides more powerful functions than BeanFactory and is generally used by developers.
3), the difference between the two interfaces
Because when we use the Spring framework, we usually use it with web pages. When we use BeanFactory to create objects, we do not create objects. When we load configuration files, we use tomcat when the server starts. The system loads files, etc. The troublesome and non-spatial things are done when tomcat starts to provide a better user experience, so the ApplicationContext interface is used
4), the implementation class of applicationContext
3.IOC operation bean management (based on xml)
1), what is bean management:
A, bean management consists of two steps: Spring object creation and Spring property injection
2), the implementation of bean management:
a, implementation based on xml configuration file
1. Create objects based on XML
id attribute: give an alias to the class path
class attribute: the full path to create the object class
Create a default object in XML by default using the null parameter constructor
2. Attribute injection based on XML (1), DI: Dependency injection, which is to inject attributes.
The difference between DI and IOC: DI is an implementation of IOC.
Method 1: Use set method to inject
(a), create an object of the class, create a set method
(b), configure object creation in the configuration file, configure property injection
Method 2: Use the parameterized construction method to inject
Method 3: p namespace injection:
first step:
Step 2:
3. Inject nulls and special characters
One, inject null value
Second, inject special symbols
4. Inject bean
1), inject external bean
Introducing external beans and calling the Dao layer with service is the process of introducing external beans.
2) Injecting inner beans and cascading assignments
Cascading assignment method 1: The get method of dept is not required.
Cascading assignment method 2: The second method needs to create a get method of dept.
5. Inject collection properties
0), create Stu class, User class
package com.yuge;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Stu {
//数组类型
private String course[];
//List类型
private List<String> name;
//Map类型
private Map<String,String> map;
//Set类型
private Set<String> set;
//List类型中存入多个对象
private List<User> userList;
public void setUserList(List<User> userList) {
this.userList = userList;
}
public void setCourse(String[] course) {
this.course = course;
}
public void setName(List<String> name) {
this.name = name;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
public void setSet(Set<String> set) {
this.set = set;
}
public void show(){
System.out.println(Arrays.toString(course));
System.out.println(name);
System.out.println(map);
System.out.println(set);
System.out.println(userList);
}
}
package com.yuge;
public class User {
private String name;
public void setName(String name) {
this.name = name;
}
public void add(){
System.out.println("add.......");
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
1) .XML injects array type properties
2), XML injection List collection property
3), XML injection Map collection properties
4), XML injection Map attribute
5), inject object properties in the collection:
<?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:m="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置Stu对象创建-->
<bean id="stu" class="com.yuge.Stu">
<!--注入数组属性-->
<property name="course">
<array>
<value>javaSe</value>
<value>Mysql</value>
</array>
</property>
<!--注入List对象-->
<property name="name">
<list>
<value>武巴</value>
<value>巴巴</value>
</list>
</property>
<!--注入Map对象-->
<property name="map">
<map>
<entry key="JAVASE" value="javase"></entry>
<entry key="SPRING" value="Spring"></entry>
</map>
</property>
<!--注入Set对象-->
<property name="set">
<set>
<value>张三</value>
<value>小三</value>
</set>
</property>
<!--在list中注入对象属性-->
<property name="userList">
<list>
<ref bean="user1"></ref>
<bean id="user1=2" class="com.yuge.User">
<property name="name" value="李华"></property>
</bean>
</list>
</property>
</bean>
<bean id="user1" class="com.yuge.User">
<property name="name" value="李烨"></property>
</bean>
</beans>
6), create a test class
package com.yuge.test;
import com.yuge.Stu;
import com.yuge.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.applet.AppletContext;
public class Tset {
@Test
public void testAdd(){
//加载配置文件
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("bean2.xml");
//创建对象
Stu stu = (Stu) applicationContext.getBean("stu");
stu.show();
}
}
7), output the result
8). Extract the collection upwards as a common collection of all beans
Step 1: Introduce a new namespace:
Step 2: Use the util tag to complete the upward extraction of list collection injection
Create a new Book class to test the upward extraction and injection of the list
package com.yuge;
import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;
import java.util.List;
public class Book {
private List<String> bookList;
public void setBookList(List<String> bookList) {
this.bookList = bookList;
}
public void test(){
System.out.println(bookList);
}
}
The method of configuring XML file extraction and injection list:
<?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:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<util:list id="list">
<value>java从入门到入土</value>
<value>python从入门到入狱</value>
</util:list>
<bean id="book" class="com.yuge.Book">
<property name="bookList" ref="list"></property>
</bean>
</beans>
Running result: Extraction succeeded
What it looks like before extraction:
What it looks like after extraction:
More objects can also be extracted.
6. Two types of beans in Spring
1) Ordinary bean: return what type is defined in XML
2), factory bean: a type is defined in XML, which can return other types
Step 1: Create a class as a factory bean and implement the FactoryBean interface
Step 2: Implement the method in the interface, and define the returned bean type in the implemented method
package com.yuge.factoryBean;
import com.yuge.Stu;
import org.springframework.beans.factory.FactoryBean;
public class Mybean implements FactoryBean<Stu> {
@Override
public Stu getObject() throws Exception {
Stu stu = new Stu();
return stu;
}
@Override
public Class<?> getObjectType() {
return null;
}
@Override
public boolean isSingleton() {
return false;
}
}
Step 3: Configure the XML file
<bean id="myBean" class="com.yuge.factoryBean.Mybean">
</bean>
测试:
@Test
public void testMyBean(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");
Stu stu = context.getBean("myBean",Stu.class);
System.out.println(stu);
}
result:
7. The scope of the bean:
Single or multiple instances when configuring beans in XML:
8. Automatic assembly of XML
Autowiring: According to the specified wiring rules, (property name or property type), Spring automatically fills in the matching property value.
Demonstration of automatic autowiring:
1. Assemble according to the name
2. Assemble according to the attribute type
9. Introduce external attribute management
4.IOC operation beans (based on annotations)
1. Spring provides annotations for creating objects
The first step is to introduce dependencies:
Step 2: Turn on component scan
Step 3: Create a class and add annotations to the class.
1, @Component, you can use the annotation to create objects
2, @Service, generally used for business logic layer, or service layer
3, @Controller, generally used for the Web layer
4, @Repository, generally used for Dao layer
The above qualification annotations have the same function, but each annotation is used in different layers for developers to distinguish.
2. Open the detailed configuration of the component scan configuration
3. Use annotations to enter and exit attributes
1), @Autowired: Automatically inject according to the property type
Step 1: Create objects in each class using annotations.
Step 2: Define object properties. Add annotations to properties. The set method is not required.
2), @Qualifier: inject according to the property name
3), @Resource: can be injected according to property name and property type
The above three are injection objects, not ordinary types *
4), @Value: inject common types
4. Fully Annotated Development
1), create a configuration class to replace the XML configuration file
2), write the test class
Three, Aop
Aspect-oriented, without modifying the source code to enhance the function.
1. What is AOP
Isolate the various logics of the business, thereby reducing the logical coupling between the businesses, improving the reusability of the code, and improving the development efficiency.
2. The underlying principle of AOP
1. The bottom layer of AOP uses dynamic proxy
1. Dynamic proxy with interface, using JDK's dynamic proxy
Create a proxy object of the implementation class of the interface and enhance the method of the class
2. Dynamic proxy without interface, use CGLIB dynamic proxy
Create a proxy object of the subclass to enhance the method of the class
2. Use JDK's dynamic proxy
Use the proxy class to implement dynamic proxies
Code:
1. Create an interface:
package com.JDK动态代理;
public interface UserDao {
public int add(int a,int b);
public String update(String id);
}
2. Create an implementation class
package com.JDK动态代理;
public class UserDaoImpl implements UserDao{
@Override
public int add(int a, int b) {
return a+b;
}
@Override
public String update(String id) {
return id;
}
}
3. Use the proxy class to create a dynamic proxy object for the interface
package com.JDK动态代理;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.security.PublicKey;
import java.security.UnresolvedPermission;
import java.util.Arrays;
public class JDKProxy {
public static void main(String[] args) {
Class[] interfaces = {UserDao.class};
UserDao dao = (UserDao)Proxy.newProxyInstance(UserDaoProxy.class.getClassLoader(), interfaces, new UserDaoProxy(new UserDaoImpl()));
int res = dao.add(1, 2);
System.out.println(res);
}
}
class UserDaoProxy implements InvocationHandler{
//需要将待增强功能的类的对象传递到代理类中,并通过构造方法,代理类的构造方法将其实例化
//通过UserDaoProxy创建UserDaoImpl的代理对象
private Object obj;
public UserDaoProxy(Object obj){
this.obj = obj;
}
@Override
/**
*增加逻辑写在这个方法内
* @ proxy:代理对象
* @ method:需要增强的方法
* @ args:要增强功能的方法需要的参数
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//方法之前
System.out.println("方法之前执行。。。"+method.getName()+"传递的参数:"+ Arrays.toString(args));
//被增强方法执行
Object res = method.invoke(obj, args);
//方法之后执行
System.out.println("方法之后执行。。。"+obj);
return res;
}
}
3. Related terms in AOP
1. Join points: Those methods that can be enhanced are called join points.
2. Entry point: The way the world is really enhanced is called entry point.
3. Notification (enhancement): The logical part that is actually enhanced is called notification or enhancement.
There are various types of notifications:
4. Aspect: The action of applying a notification to a pointcut is called an aspect
##4, Operational preparation for AOP
1. The Spring framework generally implements AOP operations based on AspectJ
AspectJ: It is not part of the Spring framework and is independent of the AOP framework. Generally, Spring and AOP frameworks are used together for AOP operations.
2. AOP operation based on AspectJ
(1), AOP operation based on XML configuration file
(2), based on annotations (use)
3. In the process of the project, introduce AOP-related dependencies.
4, the pointcut expression
(1), the function of the pointcut expression: know which method in which class to enhance.
(2), grammatical structure:
execution:([权限修饰符][返回类型][类全路径][方法名称](参数列表))
Example 1: execution(* (the return value can be omitted) com.yuge.UserDaoImpl.add(..));
Strengthen the add() method of com.yuge.UserDaoImpl, the incoming parameter is represented by .., the permission modifier is *, and the return value type is omitted.
Example 2: execution( (the return value can be omitted) com.yuge.UserDaoImpl. (..)); Strengthen all methods in the class.
Example 3: execution( (the return value can be omitted) com.yuge. .*(..)); Strengthen all methods of all classes in the package
5, AOP operation (AspectJ annotation)
1. Create a class, define a method in the class, and use annotations to enhance the method in the class.
package com.AOP注解方式;
public class User {
public void add(){
System.out.println("add...................");
}
}
2. Create an enhancement class and write enhancement logic
package com.AOP注解方式;
//增强类
public class UserProxy {
//前置通知
public void before(){
System.out.println("before.............");
}
}
3. Configure the notification
(0), the introduction of namespace
(1), in the spring configuration file, enable annotation scanning
<!--开启注解扫描-->
<context:component-scan base-package="com.AOP注解方式"></context:component-scan>
(2), use annotations to create User objects and UserProxy objects.
(3), add the @Aspect annotation to the enhanced class
(4), enable the generation of proxy objects in the spring configuration file.
<!--Open AspectJ to generate proxy objects-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
(5), configure different types of notifications
a,在增强类方法上面,添加通知类型。使用切入点表达式配置
package com.AOP注解方式;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
//增强类
@Component
@Aspect //生成代理对象
public class UserProxy {
//前置通知,添加了Before注解,则就会在add()方法之前执行before方法。
@Before("execution(* com.AOP注解方式.User.add(..))")
public void before(){
System.out.println("before.............");
}
//在方法执行之后执行
@After("execution(* com.AOP注解方式.User.add(..))")
public void after(){
System.out.println("after.............");
}
//在方法存在异常时执行
@AfterThrowing("execution(* com.AOP注解方式.User.add(..))")
public void afterThrowing(){
System.out.println("afterThrowing.............");
}
//在方法返回之后执行
@AfterReturning("execution(* com.AOP注解方式.User.add(..))")
public void afterReturning(){
System.out.println("afterReturning.............");
}
//添加环绕方法,在方法执行前后都执行
@Around("execution(* com.AOP注解方式.User.add(..))")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕之前.............");
//被增强的方法执行
proceedingJoinPoint.proceed();
System.out.println("环绕之后..............");
}
}
package com.AOP注解方式;
import org.springframework.stereotype.Component;
@Component
public class User {
public void add(){
System.out.println("add...................");
}
}
package com.AOP注解方式;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
@org.junit.Test
public void testAdd(){
//加载上下文配置,读取xml配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
//获取对象
User user = (User)context.getBean("user");
user.add();
}
}
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--开启注解扫描-->
<context:component-scan base-package="com.AOP注解方式"></context:component-scan>
<!--开启AspectJ生成代理对象-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<bean id="user" class="com.AOP注解方式.User"></bean>
</beans>
operation result:
b, summary:
after无论是否存在异常都会执行,afterReturning存在异常时不会执行。
6, AOP operation (AspextJ annotation) optimization
1. Extract the same entry point
//抽取相同的切入点
@Pointcut(value = "execution(* com.AOP注解方式.User.add(..))")
public void pointCut(){
}
//前置通知,添加了Before注解,则就会在add()方法之前执行before方法。
@Before("pointCut()")
public void before(){
System.out.println("before.............");
}
//在方法执行之后执行
@After("execution(* com.AOP注解方式.User.add(..))")
public void after(){
System.out.println("after.............");
}
2. When there are multiple enhancement classes that enhance the same method, set the enhancement class priority
Use the @Order (integer value) annotation to set priorities on multiple enhanced classes. The smaller the integer value, the higher the priority.
//增强类
@Component
@Aspect //生成代理对象
@Order(3)
public class UserProxy {
//抽取相同的切入点
@Pointcut(value = "execution(* com.AOP注解方式.User.add(..))")
public void pointCut(){
}
@Component
@Aspect
@Order(0)
public class UserProxy2 {
@Before("execution(* com.AOP注解方式.User.add(..))")
public void before(){
System.out.println("UserProxy2增强类先执行。。。。。");
}
}
7, AOP operation (XML configuration file)
The premise is to create objects of the enhanced class and the enhanced class in xml
8. Fully Annotated Development
Four, JdbcTemplate
1. The concept of JdbcTempalte
Spring encapsulates JDBC, and using JdbcTemplate can facilitate the operation of the database.
Ready to work:
Import dependencies:
Configure XML to create class injection properties
2. Use the JdbcTemplate template to add, delete, modify and check the database
<context:component-scan base-package="com"/>
<bean id = "dataSource" class="com.druid.DruidDataSource" destroy-method="close">
<property name="url" value="jdbc:mysql://localhost:3306/jdbc_db"/>
<property name="username" value="root"/>
<property name="password" value="3.141592654"/>
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入dataSource对象-->
<property name="dataSource" ref="dataSource"></property>
</bean>
public interface BookDao {
void add(Book book);
}
@Repository
public class BookDaoImpl implements BookDao {
//注入JdbcTemplate对象
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void add(Book book) {
String sql = "insert into book values(?,?,?)";
int update = jdbcTemplate.update(sql, book.getId(), book.getName(), book.getPrice());
System.out.println(update);
}
}
@Service
public class BookService {
//注入BookDao属性
@Autowired
private BookDao bookDao;
public void insert(Book book){
bookDao.add(book);
}
}
package com.druid;
public class DruidDataSource {
String url;
String password;
String username;
String driverClassName;
public void setUrl(String url) {
this.url = url;
}
public void setPassword(String password) {
this.password = password;
}
public void setUsername(String username) {
this.username = username;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
private void close() {
}
}
package com.test;
import com.bean.Book;
import com.service.BookService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestJdbcTemplate {
@Test
public void test(){
ApplicationContext context =
new ClassPathXmlApplicationContext("bean4.xml");
BookService bookService = context.getBean("bookService", BookService.class);
Book book = new Book();
book.setId(1);
book.setName("一阳指");
book.setPrice(250);
bookService.insert(book);
}
}
query returns a value
query returns an object
query returns a collection
## 3, batch operations on the database using the JdbcTemplate template
Five, business operations
1. The concept of transaction:
To recap: A transaction refers to a basic set of data manipulation units, either all or none.
Typical transaction scenario: bank transfer
The four characteristics of transactions (ACID): atomicity, consistency, isolation, durability
2. The establishment of the transaction environment
3, the introduction of spring transaction management
1. Transactions are added to the Service layer (business logic layer) of the three-tier architecture of JavaEE
2. Transaction operation in Spring:
1), there are two ways: programmatic (adding code to the method) and declarative (XML-based or annotation-based)
2), declarative transaction management: the underlying use of AOP
3), Spring transaction management related API
4. The propagation behavior of transactions between multiple transactions:
5, ioslation about the isolation level of the transaction:
Isolation of transactions: operations of multiple transactions do not affect each other
If isolation is not considered: it will lead to dirty reads, phantom reads, and non-repeatable reads.
To resolve the isolation level:
Configure the isolation level:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。