Spring知识点

  • 1. Spring简介(此章略过)
    • 1.1 Spring概述
    • 1.2 Spring家族
    • 1.3 Spring Framework
  • 2. IOC
    • 2.1 IOC容器
    • 2.2 基于XML管理bean
      • 2.2.1 入门案例(ioc容器的整体思路)
      • 2.2.2 获取bean的三种方式
      • 2.2.3 依赖注入
        • 2.2.3.1 setter注入
        • 2.2.3.2 构造器注入
      • 2.2.4 特殊值处理
      • 2.2.5 为类类型属性赋值
      • 2.2.6 为数组类型属性赋值
      • 2.2.7 为集合类型属性赋值
        • 2.2.7.1 为List集合赋值
        • 2.2.7.2 为Map集合赋值
      • 2.2.8 p命名空间
      • 2.2.9 引入外部属性文件
      • 2.2.10 bean的作用域
      • 2.2.11 bean的生命周期
      • 2.2.12 FactoryBean
      • 2.2.13 基于xml的自动装配
    • 2.3 基于注解管理bean
      • 2.3.1 标记与扫描
        • 2.3.1.1 标记
        • 2.3.1.2 扫描
        • 2.3.1.3 bean的id
      • 2.3.2 基于注解的自动装配
  • 3. AOP
    • 3.1 场景模拟
    • 3.2 代理模式
    • 3.3 AOP概念及相关术语
    • 3.4 基于注解的AOP
    • 3.5 基于XML的AOP(了解)
  • 4. 声明式事务
    • 4.1 JdbcTemplate
    • 4.2 声明式事务概念
    • 4.3 基于注解的声明式事务
    • 4.4 基于XML的声明式事务

1. Spring简介(此章略过)

1.1 Spring概述

1.2 Spring家族

1.3 Spring Framework


2. IOC

2.1 IOC容器

IOC:Inversion of Control,翻译过来是反转控制。
DI:Dependency Injection,翻译过来是依赖注入。

2.2 基于XML管理bean

2.2.1 入门案例(ioc容器的整体思路)

类和方法:

文件位置:src/main/java/com/atguigu/spring/pojo/HelloWorld.java

package com.atguigu.spring.pojo;public class HelloWorld {public void sayHello(){System.out.println("hello,spring");}
}

Spring配置文件

创建方式:

文件位置:src/main/resources/applicationContext.xml

<?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"><!--bean:配置一个bean对象,将对象交给IOC容器来管理;配置HelloWorld所对应的bean,即将HelloWorld的对象交给Spring的IOC容器管理属性:id:设置bean的唯一标识class:设置bean所对应类型的全类名--><bean id="helloworld" class="com.atguigu.spring.pojo.HelloWorld"></bean>
</beans>

测试类

文件位置:src/test/java/com/atguigu/spring/test/HelloWorldTest.java

package com.atguigu.spring.test;import com.atguigu.spring.pojo.HelloWorld;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class HelloWorldTest {@Testpublic void test(){//获取IOC容器ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");//获取IOC容器中的Bean对象HelloWorld helloworld = (HelloWorld) ioc.getBean("helloworld");helloworld.sayHello();}
}

2.2.2 获取bean的三种方式

获取bean的方式:
1、根据id获取
2、根据类型获取(最常用)
3、根据id和类获取

    /*** 获取bean的三种方式:* 1、根据id获取;* 2、根据类型获取;(使用最多的方式)*  注意:根据类型获取bean时,要求IOC容器中有且只有一个类型匹配的bean。*  若没有任何一个类型匹配的bean,此时抛出异常:NoSuchBeanDefinitionException*  若有多个类型匹配的bean,此时抛出异常:NoUniqueBeanDefinitionException* 3、根据id和类型获取;*/@Testpublic void testIOC(){//获取IOC容器ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");//获取bean的第一种方法:根据id获取bean//Student studentOne = (Student) ioc.getBean("studentOne");//获取bean的第二种方法:根据类型获取beanStudent student = ioc.getBean(Student.class);//获取bean的第三种方法:根据id和类型来获取bean//Student studentOne = ioc.getBean("studentOne", Student.class);System.out.println(studentOne);}

2.2.3 依赖注入

2.2.3.1 setter注入

学生类

package com.atguigu.spring.pojo;import java.util.Arrays;
import java.util.Map;public class Student {private Integer sid;private String sname;private Integer age;private String gender;private Double score;private Clazz clazz;private String[] hobby;private Map<String,Teacher> teacherMap;@Overridepublic String toString() {return "Student{" +"sid=" + sid +", sname='" + sname + '\'' +", age=" + age +", gender='" + gender + '\'' +", score=" + score +", clazz=" + clazz +", hobby=" + Arrays.toString(hobby) +", teacherMap=" + teacherMap +'}';}public Map<String, Teacher> getTeacherMap() {return teacherMap;}public void setTeacherMap(Map<String, Teacher> teacherMap) {this.teacherMap = teacherMap;}public String[] getHobby() {return hobby;}public void setHobby(String[] hobby) {this.hobby = hobby;}public Clazz getClazz() {return clazz;}public void setClazz(Clazz clazz) {this.clazz = clazz;}public Double getScore() {return score;}public void setScore(Double score) {this.score = score;}public Integer getSid() {return sid;}public void setSid(Integer sid) {this.sid = sid;}public String getSname() {return sname;}public void setSname(String sname) {this.sname = sname;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public Student() {}public Student(Integer sid, String sname,String gender , Integer age) {this.sid = sid;this.sname = sname;this.gender = gender;this.age = age;}public Student(Integer sid, String sname, String gender, Double score) {this.sid = sid;this.sname = sname;this.gender = gender;this.score = score;}
}

spring配置文件

    <!--依赖注入-setter注入--><bean id="studentTwo" class="com.atguigu.spring.pojo.Student"><!--property:通过成员变量的set方法来进行赋值;name:需要设置需要赋值的属性名(属性名:跟get、set方法有关);value:设置为属性所赋的值;--><property name="sid" value="1001"></property><property name="sname" value="张三"></property><property name="gender" value="男"></property><property name="age" value="23"></property></bean>

测试类

    public void testDI(){//获取IOC容器ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");//setter注入Student studentTwo = ioc.getBean("studentTwo", Student.class);System.out.println(studentTwo);}

2.2.3.2 构造器注入

学生类同上(需要设置有参构造)
Spring配置文件

    <!--依赖注入-构造器注入--><bean id="studentThree" class="com.atguigu.spring.pojo.Student"><constructor-arg name="sid" value="1002"></constructor-arg><constructor-arg name="sname" value="李四"></constructor-arg><constructor-arg name="gender" value="女"></constructor-arg><constructor-arg name="age" value="24"></constructor-arg></bean>

测试类

    public void testDI(){//获取IOC容器ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");//构造器注入Student studentThree = ioc.getBean("studentThree", Student.class);System.out.println(studentThree);}

2.2.4 特殊值处理

特殊值处理:
1、赋值null
2、使用XML特殊符号赋值
3、使用CDATA节赋值

    <!--字面量的特殊值赋值处理--><bean id="studentFour" class="com.atguigu.spring.pojo.Student"><!--1、赋值null--><property name="sname"><null/></property><!--2、XML特殊符号--><property name="sname" value="&lt;王五&gt;"></property><!--3、CDATA节(内容必须放到value标签中)IDEA中输入“CD”按回车就可以在CDATA节括号内输入内容,CDATA节中的内容全部原样解析。--><property name="sname"><value><![CDATA[<王五>]]></value></property></bean>

2.2.5 为类类型属性赋值

student类

package com.atguigu.spring.pojo;import java.util.Arrays;
import java.util.Map;public class Student {private Integer sid;private String sname;private Integer age;private String gender;private Double score;private Clazz clazz;private String[] hobby;private Map<String,Teacher> teacherMap;@Overridepublic String toString() {return "Student{" +"sid=" + sid +", sname='" + sname + '\'' +", age=" + age +", gender='" + gender + '\'' +", score=" + score +", clazz=" + clazz +", hobby=" + Arrays.toString(hobby) +", teacherMap=" + teacherMap +'}';}public Map<String, Teacher> getTeacherMap() {return teacherMap;}public void setTeacherMap(Map<String, Teacher> teacherMap) {this.teacherMap = teacherMap;}public String[] getHobby() {return hobby;}public void setHobby(String[] hobby) {this.hobby = hobby;}public Clazz getClazz() {return clazz;}public void setClazz(Clazz clazz) {this.clazz = clazz;}public Double getScore() {return score;}public void setScore(Double score) {this.score = score;}public Integer getSid() {return sid;}public void setSid(Integer sid) {this.sid = sid;}public String getSname() {return sname;}public void setSname(String sname) {this.sname = sname;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public Student() {}public Student(Integer sid, String sname,String gender , Integer age) {this.sid = sid;this.sname = sname;this.gender = gender;this.age = age;}public Student(Integer sid, String sname, String gender, Double score) {this.sid = sid;this.sname = sname;this.gender = gender;this.score = score;}
}

clazz类

package com.atguigu.spring.pojo;import java.util.List;public class Clazz {private Integer cid;private String cname;private List<Student> students;@Overridepublic String toString() {return "Clazz{" +"cid=" + cid +", cname='" + cname + '\'' +", students=" + students +'}';}public List<Student> getStudents() {return students;}public void setStudents(List<Student> students) {this.students = students;}public Clazz() {}public Clazz(Integer cid, String cname) {this.cid = cid;this.cname = cname;}public Integer getCid() {return cid;}public void setCid(Integer cid) {this.cid = cid;}public String getCname() {return cname;}public void setCname(String cname) {this.cname = cname;}}

类类型赋值的三种方式

类类型赋值的三种方式:
1、引用外部已经声明的bean的方式
2、级联方式
3、内部bean方式

    <!--类类型赋值:1、引用外部已声明bean方式2、级联方式3、内部bean--><!--类类型赋值第一种方式:引用外部已声明bean方式--><bean id="studentFive" class="com.atguigu.spring.pojo.Student"><property name="sid" value="1003"></property><property name="sname" value="赵六"></property><property name="age" value="26"></property><property name="gender" value="男"></property><!--ref:引用IOC容器中的某个bean的id--><property name="clazz" ref="clazzOne"></property></bean><bean id="clazzOne" class="com.atguigu.spring.pojo.Clazz"><property name="cid" value="1111"></property><property name="cname" value="最强王者班"></property></bean><!--类类型赋值第二种方式:级联方式--><bean id="studentFiveA" class="com.atguigu.spring.pojo.Student"><property name="sid" value="1003"></property><property name="sname" value="赵六"></property><property name="age" value="26"></property><property name="gender" value="男"></property><!-- 一定先引用某个bean为属性赋值,才可以使用级联方式更新属性 --><property name="clazz" ref="clazzOne"></property><property name="clazz.cid" value="1112"></property><property name="clazz.cname" value="远大前程班"></property></bean><!--类类型赋值第三种方式:内部bean方式--><bean id="studentFiveB" class="com.atguigu.spring.pojo.Student"><property name="sid" value="1003"></property><property name="sname" value="赵六"></property><property name="age" value="26"></property><property name="gender" value="男"></property><!--内部bean:只能在当前bean的内部使用,不能直接通过IOC容器获取--><property name="clazz"><bean id="clazzInner" class="com.atguigu.spring.pojo.Clazz"><property name="cid" value="1113"></property><property name="cname" value="超级牛逼班"></property></bean></property></bean>

测试类

    @Testpublic void testDI(){//获取IOC容器ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");//类类型赋值//1、外部bean方式Student studentFive = ioc.getBean("studentFive", Student.class);System.out.println(studentFive);//外部bean是可以通过IOC容器获取的Clazz clazzOne = ioc.getBean("clazzOne", Clazz.class);System.out.println(clazzOne);//级联方式Student studentFiveA = ioc.getBean("studentFiveA", Student.class);System.out.println(studentFiveA);//内部bean方式Student studentFiveB = ioc.getBean("studentFiveB", Student.class);System.out.println(studentFiveB);//注意:内部bean是无法通过IOC容器来获取的Clazz clazzInner = ioc.getBean("clazzInner", Clazz.class);System.out.println(clazzInner); //结果异常:NoSuchBeanDefinitionException}

2.2.6 为数组类型属性赋值

student类

package com.atguigu.spring.pojo;import java.util.Arrays;
import java.util.Map;public class Student {private Integer sid;private String sname;private Integer age;private String gender;private Double score;private Clazz clazz;private String[] hobby;private Map<String,Teacher> teacherMap;@Overridepublic String toString() {return "Student{" +"sid=" + sid +", sname='" + sname + '\'' +", age=" + age +", gender='" + gender + '\'' +", score=" + score +", clazz=" + clazz +", hobby=" + Arrays.toString(hobby) +", teacherMap=" + teacherMap +'}';}public Map<String, Teacher> getTeacherMap() {return teacherMap;}public void setTeacherMap(Map<String, Teacher> teacherMap) {this.teacherMap = teacherMap;}public String[] getHobby() {return hobby;}public void setHobby(String[] hobby) {this.hobby = hobby;}public Clazz getClazz() {return clazz;}public void setClazz(Clazz clazz) {this.clazz = clazz;}public Double getScore() {return score;}public void setScore(Double score) {this.score = score;}public Integer getSid() {return sid;}public void setSid(Integer sid) {this.sid = sid;}public String getSname() {return sname;}public void setSname(String sname) {this.sname = sname;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public Student() {}public Student(Integer sid, String sname,String gender , Integer age) {this.sid = sid;this.sname = sname;this.gender = gender;this.age = age;}public Student(Integer sid, String sname, String gender, Double score) {this.sid = sid;this.sname = sname;this.gender = gender;this.score = score;}
}

bean配置

    <!--数组类型的属性赋值--><bean id="studentFiveC" class="com.atguigu.spring.pojo.Student"><property name="sid" value="1003"></property><property name="sname" value="赵六"></property><property name="age" value="26"></property><property name="gender" value="男"></property><property name="clazz"><bean id="clazzInner" class="com.atguigu.spring.pojo.Clazz"><property name="cid" value="1113"></property><property name="cname" value="超级牛逼班"></property></bean></property><property name="hobby"><array><!--如果当前使用的是字面量类型则使用value,如果使用的是类类型的则使用ref--><value>抽烟</value><value>喝酒</value><value>烫头</value></array></property></bean>

测试类

    @Testpublic void testDI(){//获取IOC容器ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");//数组类型的属性值Student studentFiveC = ioc.getBean("studentFiveC", Student.class);System.out.println(studentFiveC);}

2.2.7 为集合类型属性赋值

2.2.7.1 为List集合赋值

clazz类

package com.atguigu.spring.pojo;import java.util.List;public class Clazz {private Integer cid;private String cname;private List<Student> students;@Overridepublic String toString() {return "Clazz{" +"cid=" + cid +", cname='" + cname + '\'' +", students=" + students +'}';}public List<Student> getStudents() {return students;}public void setStudents(List<Student> students) {this.students = students;}public Clazz() {}public Clazz(Integer cid, String cname) {this.cid = cid;this.cname = cname;}public Integer getCid() {return cid;}public void setCid(Integer cid) {this.cid = cid;}public String getCname() {return cname;}public void setCname(String cname) {this.cname = cname;}}

bean配置

    <!--List集合类型的属性赋值--><bean id="clazzTwo" class="com.atguigu.spring.pojo.Clazz"><property name="cid" value="1111"></property><property name="cname" value="最强王者班"></property><!--方法一:在内部bean--><property name="students"><list><!--如果当前使用的是字面量类型则使用value,如果使用的是类类型的则使用ref--><ref bean="studentOne"></ref><ref bean="studentTwo"></ref><ref bean="studentThree"></ref></list></property><!--方法二:在外部声明一个list的集合,然后在内部使用ref引用--><property name="students" ref="studentList"></property></bean><!--配置一个集合类型的bean,需要使用util的约束--><util:list id="studentList"><ref bean="studentOne"></ref><ref bean="studentTwo"></ref><ref bean="studentThree"></ref></util:list>

测试类

    @Testpublic void testDI(){//获取IOC容器ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");//List集合类型的属性值Clazz clazzTwo = ioc.getBean("clazzTwo", Clazz.class);System.out.println(clazzTwo);}

2.2.7.2 为Map集合赋值

Teacher类

package com.atguigu.spring.pojo;public class Teacher {private Integer tid;private String tname;@Overridepublic String toString() {return "teacher{" +"tid=" + tid +", tname='" + tname + '\'' +'}';}public Teacher() {}public Teacher(Integer tid, String tname) {this.tid = tid;this.tname = tname;}public Integer getTid() {return tid;}public void setTid(Integer tid) {this.tid = tid;}public String getTname() {return tname;}public void setTname(String tname) {this.tname = tname;}
}

Student类

package com.atguigu.spring.pojo;import java.util.Arrays;
import java.util.Map;public class Student {private Integer sid;private String sname;private Integer age;private String gender;private Double score;private Clazz clazz;private String[] hobby;private Map<String,Teacher> teacherMap;@Overridepublic String toString() {return "Student{" +"sid=" + sid +", sname='" + sname + '\'' +", age=" + age +", gender='" + gender + '\'' +", score=" + score +", clazz=" + clazz +", hobby=" + Arrays.toString(hobby) +", teacherMap=" + teacherMap +'}';}public Map<String, Teacher> getTeacherMap() {return teacherMap;}public void setTeacherMap(Map<String, Teacher> teacherMap) {this.teacherMap = teacherMap;}public String[] getHobby() {return hobby;}public void setHobby(String[] hobby) {this.hobby = hobby;}public Clazz getClazz() {return clazz;}public void setClazz(Clazz clazz) {this.clazz = clazz;}public Double getScore() {return score;}public void setScore(Double score) {this.score = score;}public Integer getSid() {return sid;}public void setSid(Integer sid) {this.sid = sid;}public String getSname() {return sname;}public void setSname(String sname) {this.sname = sname;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public Student() {}public Student(Integer sid, String sname,String gender , Integer age) {this.sid = sid;this.sname = sname;this.gender = gender;this.age = age;}public Student(Integer sid, String sname, String gender, Double score) {this.sid = sid;this.sname = sname;this.gender = gender;this.score = score;}
}

Bean配置

    <!--map集合类型的属性赋值--><bean id="studentFiveD" class="com.atguigu.spring.pojo.Student"><property name="sid" value="1003"></property><property name="sname" value="赵六"></property><property name="age" value="26"></property><property name="gender" value="男"></property><property name="clazz"><bean id="clazzInner" class="com.atguigu.spring.pojo.Clazz"><property name="cid" value="1113"></property><property name="cname" value="超级牛逼班"></property></bean></property><property name="hobby"><array><!--如果当前使用的是字面量类型则使用value,如果使用的是类类型的则使用ref--><value>抽烟</value><value>喝酒</value><value>烫头</value></array></property><!--Map集合属性值赋值第一种方式:内部--><property name="teacherMap"><map><entry key="10086" value-ref="teacherOne"></entry><entry key="10087" value-ref="teacherTwo"></entry></map></property><!--Map集合属性值赋值第二种方式:外部--><property name="teacherMap" ref="teacherMap"></property></bean><bean id="teacherOne" class="com.atguigu.spring.pojo.Teacher"><property name="tid" value="10086"></property><property name="tname" value="大宝"></property></bean><bean id="teacherTwo" class="com.atguigu.spring.pojo.Teacher"><property name="tid" value="10087"></property><property name="tname" value="小宝"></property></bean><util:map id="teacherMap"><entry key="10086" value-ref="teacherOne"></entry><entry key="10087" value-ref="teacherTwo"></entry></util:map>

测试类

    @Testpublic void testDI(){//获取IOC容器ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");//Map集合类型的属性值Student studentFiveD = ioc.getBean("studentFiveD", Student.class);System.out.println(studentFiveD);}

2.2.8 p命名空间

bean配置

    <!--p命名空间--><bean id="studentSix" class="com.atguigu.spring.pojo.Student"p:sid="1005" p:sname="小明" p:teacherMap-ref="teacherMap"></bean>

测试类

    @Testpublic void testDI(){//获取IOC容器ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");//p命名空间Student studentSix = ioc.getBean("studentSix", Student.class);System.out.println(studentSix);}

2.2.9 引入外部属性文件

依赖

        <!-- MySQL驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.16</version></dependency><!-- 数据源 --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.31</version></dependency>

外部属性文件

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/ssm?serverTimezone=UTC
jdbc.username=root
jdbc.password=root

bean配置

<?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 https://www.springframework.org/schema/context/spring-context.xsd"><!--Spring管理数据源--><!--<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">--><!--    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>--><!--    <property name="url" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC"></property>--><!--    <property name="username" value="root"></property>--><!--    <property name="password" value="root"></property>--><!--</bean>--><!--引入jdbc.properties文件--><context:property-placeholder location="jdbc.properties"></context:property-placeholder><!--通过${key}的方式访问value--><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="${jdbc.driver}"></property><property name="url" value="${jdbc.url}"></property><property name="username" value="${jdbc.username}"></property><property name="password" value="${jdbc.password}"></property></bean>
</beans>

测试类

package com.atguigu.spring.test;import com.alibaba.druid.pool.DruidDataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import java.sql.SQLException;public class DataSourceTest {@Testpublic void testDataSource() throws SQLException {//获取IOC容器ApplicationContext  ioc = new ClassPathXmlApplicationContext("spring-datasource.xml");DruidDataSource dataSource = ioc.getBean(DruidDataSource.class);System.out.println(dataSource.getConnection());}
}

2.2.10 bean的作用域

user类

package com.atguigu.spring.pojo;public class User {private Integer id;private String username;private String password;private Integer age;public User() {System.out.println("生命周期1:实例化");}public User(Integer id, String username, String password, Integer age) {this.id = id;this.username = username;this.password = password;this.age = age;}public Integer getId() {return id;}public void setId(Integer id) {System.out.println("生命周期2:依赖注入");this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", password='" + password + '\'' +", age=" + age +'}';}public void initMethod(){System.out.println("生命周期3:初始化");}public void destoryMethod(){System.out.println("生命周期4:销毁");}
}

bean配置

<?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"><!--bean的作用域scope:设置bean的作用域;singleton:单例; 表示该bean所对应的对象都是同一个;(使用较多)prototype:多例; 表示该bean所对应的对象不是同一个;在WebApplicationContet环境下,还有另外两个作用域,但是不常用;(request、session)--><bean id="student" class="com.atguigu.spring.pojo.Student" scope="singleton"><property name="sid" value="1001"></property><property name="sname" value="张三"></property><property name="score" value="100"></property></bean>
</beans>

测试类

    @Testpublic void testScope(){ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-scope.xml");Student student = ioc.getBean(Student.class);Student student1 = ioc.getBean(Student.class);System.out.println(student.equals(student1));}

2.2.11 bean的生命周期

具体的生命周期
bean对象创建(调用无参构造器)
给bean对象设置属性
bean对象初始化之前操作(由bean的后置处理器负责)
bean对象初始化(需在配置bean时指定初始化方法)
bean对象初始化之后操作(由bean的后置处理器负责)
bean对象就绪可以使用
bean对象销毁(需在配置bean时指定销毁方法)
IOC容器关闭
user类

package com.atguigu.spring.pojo;public class User {private Integer id;private String username;private String password;private Integer age;public User() {System.out.println("生命周期1:实例化");}public User(Integer id, String username, String password, Integer age) {this.id = id;this.username = username;this.password = password;this.age = age;}public Integer getId() {return id;}public void setId(Integer id) {System.out.println("生命周期2:依赖注入");this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", password='" + password + '\'' +", age=" + age +'}';}public void initMethod(){System.out.println("生命周期3:初始化");}public void destoryMethod(){System.out.println("生命周期4:销毁");}
}

bean配置

<?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"><bean id="user" class="com.atguigu.spring.pojo.User" init-method="initMethod" destroy-method="destoryMethod"><property name="id" value="1"></property><property name="username" value="admin"></property><property name="password" value="123456"></property><property name="age" value="23"></property></bean><bean id="myBeanPostProcessor" class="com.atguigu.spring.process.MyBeanPostProcessor"></bean>
</beans>

bean的后置处理器

package com.atguigu.spring.process;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;public class MyBeanPostProcessor implements BeanPostProcessor {@Overridepublic Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {//此方法在bean的生命周期初始化之前执行System.out.println("MyBeanPostProcessor-->后置处理器postProcessBeforeInitialization");return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);}@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {//此方法在bean的生命周期初始化之后执行System.out.println("MyBeanPostProcessor-->后置处理器postProcessAfterInitialization");return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);}
}

测试类

    /*** 生命周期:* 1、实例化* 2、依赖注入* 3、后置处理器的postProcessBeforeInitialization* 4、初始化:需要通过bean的init-method属性来指定初始化的方法。* 5、后置处理器的postProcessAfterInitialization* 6、销毁(IOC容器关闭时候销毁):需要通过bean的destory-method属性来指定销毁的方法。** 注意:*  若bean的作用域为单例时,生命周期的(实例化、依赖注入、初始化)会在获取IOC容器的时候就执行了;*  若bean的作用域为多例时,生命周期的(实例化、依赖注入、初始化)就会在获取bean的时候执行;*/@Testpublic void test(){//bean的生命周期//ConfigurableApplicationContext是ApplicationContext的子接口,其中扩展了刷新和关闭容器的方法;ConfigurableApplicationContext ioc = new ClassPathXmlApplicationContext("spring-lifecycle.xml");User user = ioc.getBean(User.class);System.out.println(user);ioc.close();}

2.2.12 FactoryBean

UserFactoryBean类

package com.atguigu.spring.factory;import com.atguigu.spring.pojo.User;
import org.springframework.beans.factory.FactoryBean;/*** FactoryBean是一个接口,需要创建一个类实现接口。* 其中,有三个方法:*  1、getObject():通过一个对象交给IOC容器管理;*  2、getObjectType():设置所提供对象的类型;*  3、isSingleton():所提供的对象是否单例;* 当把FactoryBean的实现类配置为bean时,会将当前类中getObject()所返回的对象交给IOC容器管理。*/
public class UserFactoryBean implements FactoryBean<User> {@Overridepublic User getObject() throws Exception {return new User();}@Overridepublic Class<?> getObjectType() {return User.class;}
}

bean配置

<?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"><bean class="com.atguigu.spring.factory.UserFactoryBean"></bean>
</beans>

测试类

package com.atguigu.spring.test;import com.atguigu.spring.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class FactoryBeanTest {@Testpublic void testFactoryBean(){ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-factory.xml");User user = ioc.getBean(User.class);System.out.println(user);}
}

2.2.13 基于xml的自动装配

UserController 类

package com.atguigu.spring.controller;import com.atguigu.spring.service.UserService;
import com.atguigu.spring.service.impl.UserServiceImpl;public class UserController {private UserService userService;public UserService getUserService() {return userService;}public void setUserService(UserService userService) {this.userService = userService;}public void saveUser(){userService.saveUser();}
}

UserService 接口

package com.atguigu.spring.service;public interface UserService {/*** 保存用户信息*/void saveUser();
}

UserServiceImpl 实现类

package com.atguigu.spring.service.impl;import com.atguigu.spring.dao.UserDao;
import com.atguigu.spring.service.UserService;public class UserServiceImpl implements UserService {private UserDao userDao;public UserDao getUserDao() {return userDao;}public void setUserDao(UserDao userDao) {this.userDao = userDao;}@Overridepublic void saveUser() {userDao.saveUser();}
}

UserDao 接口

package com.atguigu.spring.dao;public interface UserDao {/*** 保存用户信息*/void saveUser();
}

UserDaoImpl 实现类

package com.atguigu.spring.dao.impl;import com.atguigu.spring.dao.UserDao;public class UserDaoImpl implements UserDao {@Overridepublic void saveUser() {System.out.println("保存成功");}
}

bean配置

<?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"><bean id="userController" class="com.atguigu.spring.controller.UserController" autowire="constructor"><!--<property name="userService" ref="userService"></property>--></bean><bean id="userService" class="com.atguigu.spring.service.impl.UserServiceImpl" autowire="constructor"><!--<property name="userDao" ref="userDao"></property>--></bean><bean id="userDao" class="com.atguigu.spring.dao.impl.UserDaoImpl"></bean>
</beans>

测试类

package com.atguigu.spring.test;import com.atguigu.spring.controller.UserController;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class AutowireByXMLTest {/*** 自动装配:* 根据指定的策略,在IOC容器中匹配某个bean,自动为bean中的类类型的属性或接口类型的属性赋值。* 可以通过bean标签中的autowire属性来设置自动装配的策略。* 自动装配的策略:* 1、no,default:表示不装配,即bean中的属性不会自动匹配某个bean为属性赋值,此时属性使用默认值。* 2、byType:根据当前要赋值的属性的类型,在IOC容器中匹配某个bean,为属性赋值。*  注意:*      (1)若通过类型没有找到任何一个类型匹配的bean,此时属性就不装配,属性使用的默认值。默认值为null。*      (2)若通过类型找到了多个类型匹配的bean,则此时会抛出异常NoUniqueBeanDefinitionException。*      总结:当使用byType实现自动装配时,IOC容器有且只有一个类型匹配的bean能够为属性赋值。* 3、byName:将要赋值的属性的属性名作为bean的id在IOC容器中匹配到某个bean,为属性赋值。*  总结:当使用byType类型匹配的bean有多个时,此时可以使用byName来实现自动装配。*/@Testpublic void testAutowire(){ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-autowire-xml.xml");UserController userController = ioc.getBean(UserController.class);userController.saveUser();}
}

2.3 基于注解管理bean

依赖 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.atguigu.spring</groupId><artifactId>spring_ioc_annotation</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><dependencies><!-- 基于Maven依赖传递性,导入spring-context依赖即可导入当前所需所有jar包 --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.3.1</version></dependency><!-- junit测试 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency></dependencies><properties><maven.compiler.source>19</maven.compiler.source><maven.compiler.target>19</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties></project>

2.3.1 标记与扫描

2.3.1.1 标记

标记组件常用的注解:
1、@Component:将类标识为普通组件
2、@Controller:将类标识为控制层组件
3、@Service:将类标识为业务层组件
4、@Repository:将类标识为持久层组件
注意:
四个注解没有本质的区别,功能都是一样的,只是为了给程序开发人员可观。

控制层组件

@Controller
public class UserController {}

业务层接口

public interface UserService {}

业务层组件

@Service
public class UserServiceImpl implements UserService {}

持久层接口

public interface UserDao {}

持久层组件

@Repository
public class UserDaoImpl implements UserDao {}

2.3.1.2 扫描

扫描组件的三种方式:
1、最基本的扫描方式
2、指定要排除的组件
3、仅扫描指定组件

1、最基本的扫描方式

    <!--1、最基本的扫描方式--><context:component-scan base-package="com.atguigu.spring"></context:component-scan>

2、指定要排除的组件

    <!--2、指定要排除的组件--><!--context:exclude-filter 排除扫描type="annotation" 扫描方式:根据注解的类型进行排除;  expression:设置排除的注解的全类名type="assignable" 扫描方式:根据类型进行排除  expression:需要设置排除的类的全类型--><context:component-scan base-package="com.atguigu.spring"><!--将控制层组件排除掉--><!--根据注解排除掉(使用较多):到具体的类的注解处,复制路径:org.springframework.stereotype.Controller--><!--<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>--><!--根据类型排除掉--><!--<context:exclude-filter type="assignable" expression="com.atguigu.spring.controller.UserController"/>--></context:component-scan>

3、仅扫描指定组件

    <!--3、仅扫描指定组件--><!--context:include-filter 包含扫描注意:需要在context:component-scan标签中设置use-default-filters="false"use-default-filters="true" (默认为true)所设置的包下所有的类都需要扫描,此时可以使用排除扫描use-default-filters="false" 所设置的包下所有的类都不需要扫描,此时可以使用包含扫描--><context:component-scan base-package="com.atguigu.spring" use-default-filters="false"><!--只扫描,根据注解--><context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan>

2.3.1.3 bean的id

bean的id的设置
1、默认的bean的id
2、自定义的bean的id

 /*** 1、默认bean的id:*  通过注解+扫描所配置的bean的id,默认值为类的小驼峰,即类名的首字母为小写的结果值* 2、自定义bean的id:*  可通过标识组件的注解的value属性设置自定义的bean的id*/@Testpublic void test(){ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc-annotation.xml");// userController为默认的bean的idUserController userController = ioc.getBean("userController",UserController.class);System.out.println(userController);// service为自定义的bean的idUserService userService = ioc.getBean("service",UserService.class);System.out.println(userService);UserDao userDao = ioc.getBean(UserDao.class);System.out.println(userDao);}

2.3.2 基于注解的自动装配

在UserController中声明UserService对象
在UserServiceImpl中声明UserDao对象

在成员变量上直接标记@Autowired注解即可完成自动装配,不需要提供setXxx()方法。以后我们在项
目中的正式用法就是这样。

@Autowired注解的工作流程

UserController

package com.atguigu.spring.controller;import com.atguigu.spring.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;@Controller
public class UserController {//(1)@Autowired标识在成员变量上//@Autowiredprivate UserService userService;//(2)@Autowired标识在set方法上//@Autowired//public void setUserService(UserService userService) {//    this.userService = userService;//}//(3)@Autowired标识在有参构造上@Autowiredpublic UserController(UserService userService) {this.userService = userService;}public void saveUser(){userService.saveUser();}
}

UserService

package com.atguigu.spring.service;public interface UserService {/*** 保存用户信息*/void saveUser();
}

UserServiceImpl

package com.atguigu.spring.service.impl;import com.atguigu.spring.dao.UserDao;
import com.atguigu.spring.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service("service")
public class UserServiceImpl implements UserService {@Autowiredprivate UserDao userDao;@Overridepublic void saveUser() {userDao.saveUser();}
}

UserDao

package com.atguigu.spring.dao;public interface UserDao {/*** 保存用户信息*/void saveUser();
}

UserDaoImpl

package com.atguigu.spring.dao.impl;import com.atguigu.spring.dao.UserDao;
import org.springframework.stereotype.Repository;@Repository
public class UserDaoImpl implements UserDao {@Overridepublic void saveUser() {System.out.println("保存成功");}
}

测试类

package com.atguigu.spring.test;import com.atguigu.spring.controller.UserController;
import com.atguigu.spring.dao.UserDao;
import com.atguigu.spring.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class IOCByAnnotationTest {/*** 四个注解:*  1、@Component:将类标识为普通组件*  2、@Controller:将类标识为控制层组件*  3、@Service:将类标识为业务层组件*  4、@Repository:将类标识为持久层组件* 四个注解没有本质的区别,功能都是一样的,只是为了给程序开发人员可观。** 1、默认bean的id:*  通过注解+扫描所配置的bean的id,默认值为类的小驼峰,即类名的首字母为小写的结果值* 2、自定义bean的id:*  可通过标识组件的注解的value属性设置自定义的bean的id** @Autowired:实现自动装配功能的注解* 1、@Autowired注解能够标识的位置:*  (1)标识在成员变量上,此时不需要来设置成员变量的set方法;*  (2)标识在set方法上;*  (3)标识为当前成员变量赋值的有参构造上;* 2、@Autowired注解的原理*  (1)默认通过byType的方式,在IOC容器中通过类型匹配某个bean为属性赋值;*  (2)若有多个类型匹配的bean,此时会自动转换为byName的方式来实现自动装配的效果;*      (即将要赋值的属性的属性名作为bean的id匹配某个bean来为当前属性赋值)*  (3)若byType和byName的方式都无法实现自动装配,*      即IOC容器中有多个类型匹配的bean,且这些bean的id和要赋值的属性的属性名都不一致。*      此时,抛出异常:NoUniqueBeanDefinitionException*  (4)此时可以在要赋值的属性上,添加一个注解@Qualifier(""),根据@Qualifier注解中指定的名称作为bean的id进行匹配** 注意:若IOC容器中没有任何一个类型匹配的bean,此时抛出异常:NoSuchBeanDefinitionException*  在@Autowired注解中有个属性required,默认值为true,要求必须完成自动装配*  可以将required属性设置为false,此时能装配则装配,无法装配则使用属性的默认值*/@Testpublic void test(){ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc-annotation.xml");UserController userController = ioc.getBean("userController",UserController.class);userController.saveUser();}
}

3. AOP

3.1 场景模拟

3.2 代理模式

3.3 AOP概念及相关术语

3.4 基于注解的AOP

3.5 基于XML的AOP(了解)


4. 声明式事务

4.1 JdbcTemplate

4.2 声明式事务概念

4.3 基于注解的声明式事务

4.4 基于XML的声明式事务


Spring知识点记录相关推荐

  1. SpringMVC知识点记录

    SpringMVC知识点记录 1. SpringMVC简介 2. 入门案例 3. @RequestMapping注解 3.1 @RequestMapping注解的功能 3.2 @RequestMapp ...

  2. 80%以上Javaer可能不知道的一个Spring知识点

    点击蓝色"程序猿DD"关注我哟 加个"星标",不忘签到哦 来源:字节观 关注我,回复口令获取可获取独家整理的学习资料: - 001 :领取<Spring ...

  3. javaweb基础知识点记录2

    javaweb基础知识点记录 1.在service方法中,首先获得请求的方法名,然后根据方法名调用对应的doXXXX方法,比如说请求参数为GET,那么就会去调用doGet方法,请求参数为POST,那么 ...

  4. javaweb基础知识点记录1

    javaweb基础知识点记录 1.当我们通过在浏览器的输入栏中直接输入网址的方式访问网页的时候,浏览器采用的就是GET方法向服务器获取资源. 2.我们可以将Servlet看做是嵌套了HTML代码的ja ...

  5. Spring知识点总结-3

    Spring知识点总结-3:拦截 http://tianya23.blog.51cto.com/1081650/417035 http://tianya23.blog.51cto.com/108165 ...

  6. 毕业论文知识点记录(四)——MaxEnt模型

    毕业论文知识点记录(四)--MaxEnt模型 0 序言 经过了几次文章分享,数据已经准备得差不多了,师姐说可以先利用现有数据跑一个结果,然后再逐步增加想要的环境数据,改善结果. 另外,谨记师姐的一句话 ...

  7. 毕业论文知识点记录(六)——基于R语言优化maxent模型

    毕业论文知识点记录(六)--基于R语言优化maxent模型 第一步:R安装 这个网上都有很多详细的步骤,就不再详细介绍了. 第二步:R安装包 因为优化maxent模型需要用到kuenm程序包,但是官网 ...

  8. 毕业论文知识点记录(三)——SPSS去相关

    毕业论文知识点记录(三)--SPSS去相关 #(一)数据下载 1.草地贪夜蛾的发生记录,这个数据在前面文章中有描述.草地贪夜蛾发生记录下载 2.气候数据 数据来源:worldclim 我选择的分辨率是 ...

  9. 油猴脚本——掘金Markdown格式适配器知识点记录【油猴脚本、Markdown、浏览器文件读取、tooltip、SVG、、模拟用户输入、aria-xxxx属性、剪切板操作、】

    油猴脚本--掘金Markdown格式适配器知识点记录 脚本更新日志 参考:掘金Markdown格式适配器更新日志 - 掘金 脚本地址: 更新:2021年9月3日19:57:35 参考:掘金Markdo ...

最新文章

  1. MySQL数据库+命令大全+常用操作
  2. js字母大小写字母转换
  3. 操作无法完成.键入的打印机名不正确,或者指定的打印机没有连接到服务器上.有关详细信息,请单帮助...
  4. break 和continue在循环中起到的作用
  5. 新开窗口不被拦截的方法-window.open和表单提交form
  6. gevent queue应用2 队列设置了最大数量限制
  7. 水声定位中的CBF波束形成原理
  8. [云炬创业管理笔记]第四章把握创业机会测试6
  9. linux 监控命令行输入,监控 Linux 容器性能的命令行神器
  10. 【WPF】资源--《深入浅出WPF》by刘铁锰
  11. PLC可编程控制器的应用
  12. [shell][原创]shell脚本遍历文件夹下所有文件
  13. 向日葵远程软件连接Ubuntu无法显示桌面之解决方案
  14. lua 斗地主癞子牌型检测中使用递归
  15. 关于阻抗设计的建议-来至深南电路板厂的心水总结
  16. 韩寒式的幽默-屌丝回忆录
  17. 奇异网盘点全球10大最荒诞的“时髦”事件
  18. 100层楼和两个玻璃球的问题
  19. oracle12c数据库命令,oracle 12c 常用命令
  20. 以大学生活为主题html,大学生活散文800字范文-以校园生活为话题的抒情散文800字?...

热门文章

  1. x265 1.8版本更新
  2. 人工智能技术知识图谱
  3. 实用又救急!快速恢复误删文件!
  4. 关于文件句柄数和文件描述符的区分
  5. 典型相关分析(Canonical correlation analysis)(二):原始变量与典型变量之间的相关性 、典型相关系数的检验
  6. Archlinux笔记本发射热点create_ap
  7. 安装docker和docker的开机启动及容器的开机自启
  8. Oracle:ORA-00054 资源正忙
  9. 软件工程大作业进度报告
  10. uml-----什么是UML