新建maven module
引入依赖
<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>
public class HelloWorld {
public void sayHello(){
System.out.println(
"hello Spring"
);
}
}
<?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容器管理
属性:
id:bean的唯一标识,不能重复
class:设置bean对象所对应的类型
-->
<bean id="helloworld" class="com.atguigu.spring.pojo.HelloWorld"></bean>
</beans>
public class HelloWorldTest {
@Test
public void test(){
//获取ioc容器
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取ioc容器中的bean对象
HelloWorld helloworld = (HelloWorld) ioc.getBean("helloworld");
helloworld.sayHello();
}
}
获取bean的三种方式:
根据bean的id进行获取 Student student1 = (Student) ioc.getBean("student1"); 详情见实验一
根据bean的类型进行获取 Student student = ioc.getBean(Student.class);
例: 测试类:
@Test
public void testDiSet(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
Student student2 = ioc.getBean(Student.class);
System.out.println(student2);
}
配置文件:
<bean id="student1" class="com.atguigu.spring.pojo.Student"></bean>
例: 测试类:
@Test
public void testDiSet(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
Student student2 = ioc.getBean("student2", Student.class);
System.out.println(student2);
}
注意:根据类型获取bean时,要求ioc容器中有且只有一个ioc类型匹配的bean,若没有任何一个类型匹配的bean,则抛出异常
例:
<bean id="helloworldOne" class="com.atguigu.spring.bean.HelloWorld"></bean>
<bean id="helloworldTwo" class="com.atguigu.spring.bean.HelloWorld"></bean>
抛出异常:
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.atguigu.spring.bean.HelloWorld' available: expected single matching bean but
found 2: helloworldOne,helloworldTwo
结论: 根据类型来获取bean时,在满足bean唯一性的前提之下,其实只是看:(对象 instanceof 指定的类型)的返回结果,只要返回为true就可以认定为和类型匹配,能够获取到。 即通过bean的类型,bean所继承的类的类型,bean所实现的接口的类型都可以获取bean对象(注:如果一个接口有多个实现类,这些实现类都配置了 bean,根据接口类型不可以获取 bean)
方法一:setter注入
setter注入主要是通过<property>标签为对象设置属性,并通过属性进行赋值
public class Student implements Person{
private Integer id;
private String name;
private String gender;
private Integer age;
private String[] hobby;
private Clazz clazz;
private Map<String,Teacher> teacherMap;
public Student(Integer id, String name, String gender, Integer age,Clazz clazz) {
this.id = id;
this.name = name;
this.gender = gender;
this.age = age;
this.clazz = clazz;
}
public Student(Integer id, String name, String gender, Integer age) {
this.id = id;
this.name = name;
this.gender = gender;
this.age = age;
}
public Student() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, Teacher> getTeacherMap() {
return teacherMap;
}
public void setTeacherMap(Map<String, Teacher> teacherMap) {
this.teacherMap = teacherMap;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
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;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", gender='" + gender + '\'' +
", age=" + age +
", hobby=" + Arrays.toString(hobby) +
", clazz=" + clazz +
", teacherMap=" + teacherMap +
'}';
}
}
<bean id="student2" class="com.atguigu.spring.pojo.Student">
<!--
property:通过成员变量的set方法进行赋值
name:设置需要赋值的属性名(和set方法有关系)(与set get方法有关,与成员变量无关)
value:指定属性的值
-->
<property name="id" value="1001"></property>
<property name="name" value="老刘"/>
<property name="age" value="13"/>
<property name="gender" value="男"/>
</bean>
@Test
public void testDiSet(){
//测试依赖注入之set注入<property>
ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
Student student2 = ioc.getBean("student2", Student.class);
System.out.println(student2);
}
方法二:构造器注入
public Student(Integer id, String name, Integer age, String sex) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
<!-- 如果在实体类中已经设置有参构造器,可以直接根据有参构造器中属性的顺序进行value赋值,不需要写name标签-->
<bean id="studentTwo" class="com.atguigu.spring.bean.Student">
<constructor-arg value="1002"></constructor-arg>
<constructor-arg value="李四"></constructor-arg>
<constructor-arg value="33"></constructor-arg>
<constructor-arg value="女"></constructor-arg>
</bean>
注意: constructor-arg标签还有两个属性可以进一步描述构造器参数:
index属性:指定参数所在位置的索引(从0开始)
name属性:指定参数名
@Test
public void testDiGZQ(){
//测试依赖注入之构造器注入<constructor-arg>
ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
Student student2 = ioc.getBean("student4", Student.class);
System.out.println(student2);
}
前提:
public class Clazz {
private Integer clazzId;
private String clazzName;
public Integer getClazzId() {
return clazzId;
}
public void setClazzId(Integer clazzId) {
this.clazzId = clazzId;
}
public String getClazzName() {
return clazzName;
}
public void setClazzName(String clazzName) {
this.clazzName = clazzName;
}
@Override
public String toString() {
return "Clazz{" +
"clazzId=" + clazzId +
", clazzName='" + clazzName + '\'' +
'}';
}
public Clazz() {
}
public Clazz(Integer clazzId, String clazzName) {
this.clazzId = clazzId;
this.clazzName = clazzName;
}
}
private Clazz clazz;
public Clazz getClazz() {
return clazz;
}
public void setClazz(Clazz clazz) {
this.clazz = clazz;
}
操作:
方式一:引用外部已声明的bean(使用ref引用为类赋值(外部bean)):
本质:在Student的bean之外配置clazz的bean,接着在Student的bean中使用ref属性引用外部的clazz的bean
配置bean:
<bean id="student5" class="com.atguigu.spring.pojo.Student">
<property name="id" value="1005"/>
<property name="name" value="赵六"/>
<property name="gender" value="男"/>
<property name="age" value="34"/>
<!--ref:引用ioc容器中的某个bean的id-->
<property name="clazz" ref="Clazz1"/>
</bean>
<bean id="Clazz1" class="com.atguigu.spring.pojo.Clazz">
<property name="cId" value="01"/>
<property name="cname" value="外部班"/>
</bean>
注意:
如果错把ref属性写成了value属性,会抛出异常:Caused by: java.lang.IllegalStateException:Cannot convert value of type 'java.lang.String' to required type'com.atguigu.spring.bean.Clazz' for property 'clazz': no matching editors or conversion strategy found
意思是不能把String类型转换成我们要的Clazz类型,说明我们使用value属性时,Spring只把这个属性看做一个普通的字符串,不会认为这是一个bean的id,更不会根据它去找到bean来赋值
方式二:引用内部bean
本质:在一个bean中再声明一个bean就是内部bean
配置bean:
<bean id="student6" class="com.atguigu.spring.pojo.Student">
<property name="id" value="1006"/>
<property name="name" value="赵琼琼"/>
<property name="gender" value="女"/>
<property name="age" value="34"/>
<!--ref:引用ioc容器中的某个bean的id-->
<property name="clazz" >
<bean id="clazzInner" class="com.atguigu.spring.pojo.Clazz">
<property name="cId" value="02"/>
<property name="cname" value="内部班"/>
</bean>
</property>
</bean>
注意:内部bean只能在bean的内部使用,无法通过ioc容器直接获取
方式三:使用级联属性更新赋值
前提:存在外部bean,使用级联需要先引用外部bean,才能使用级联的方式进行属性的更新\
配置bean:
<bean id="studentFour" class="com.atguigu.spring.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="赵六"></property>
<property name="age" value="26"></property>
<property name="sex" value="女"></property>
<property name="clazz" ref="clazzOne"></property>
<property name="clazz.clazzId" value="3333"></property>
<property name="clazz.clazzName" value="最强王者班"></property>
</bean>
级联的方式可以看作是外部bean的扩展,对已引用的外部bean的属性进行更新操作
前提:
在Student类中添加以下代码:
private String[] hobbies;
public String[] getHobbies() {
return hobbies;
}
public void setHobbies(String[] hobbies) {
this.hobbies = hobbies;
}
<bean id="student7" class="com.atguigu.spring.pojo.Student">
<property name="id" value="1007"/>
<property name="name" value="赵琼"/>
<property name="gender" value="女"/>
<property name="age" value="34"/>
<property name="hobby" >
<array>
<value>抽烟</value>
<value>喝酒</value>
</array>
</property>
</bean>
本质:使用array标签的ref属性引用外部的bean
<bean id="student8" class="com.atguigu.spring.pojo.Student">
<property name="id" value="1007"/>
<property name="name" value="赵琼"/>
<property name="gender" value="女"/>
<property name="age" value="34"/>
<property name="clazz" >
<array>
<ref bean="Clazz3"></ref>
</array>
</property>
</bean>
<bean id="Clazz3" class="com.atguigu.spring.pojo.Clazz">
<property name="cId" value="03"/>
<property name="cname" value="数组班"/>
</bean>
方式一:通过list标签为list集合进行赋值
本质:通过list标签为list集合进行赋值,若list中为字面量类型,可直接使用value,若为类类型,则需要使用ref进行引用
前提: 在Clazz类中添加以下代码:
private List<Student> students;
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
配置bean:
<bean id="clazzList" class="com.atguigu.spring.pojo.Clazz">
<property name="cId" value="04"/>
<property name="cname" value="list班"/>
<property name="students">
<list>
<ref bean="student1"/>
<ref bean="student2"/>
<ref bean="student3"/>
</list>
</property>
</bean>
其中引用的student1,student2,student3皆为外部bean
若为Set集合类型属性赋值,只需要将其中的list标签改为set标签即可
方式二:使用util约束以及外部bean为list进行赋值,过程类似外部bean引用
<bean id="clazzListWithBeanOuter" class="com.atguigu.spring.pojo.Clazz">
<property name="cId" value="05"/>
<property name="cname" value="list班(外部引入bean)"/>
<property name="students" ref="studentList"/>
</bean>
<util:list id="studentList">
<ref bean="student1"/>
<ref bean="student2"/>
<ref bean="student3"/>
</util:list>
其中引用的student1,student2,student3皆为外部bean
前提:创建教师类Teacher:
public class Teacher {
private Integer teacherId;
private String teacherName;
public Integer getTeacherId() {
return teacherId;
}
public void setTeacherId(Integer teacherId) {
this.teacherId = teacherId;
}
public String getTeacherName() {
return teacherName;
}
public void setTeacherName(String teacherName) {
this.teacherName = teacherName;
}
public Teacher(Integer teacherId, String teacherName) {
this.teacherId = teacherId;
this.teacherName = teacherName;
}
public Teacher() {
}
@Override
public String toString() {
return "Teacher{" +"teacherId=" + teacherId +
", teacherName='" + teacherName + '\'' +'}';
}
}
在Student类中添加以下代码:
private Map<String, Teacher> teacherMap;
public Map<String, Teacher> getTeacherMap() {
return teacherMap;
}
public void setTeacherMap(Map<String, Teacher> teacherMap) {
this.teacherMap = teacherMap;
}
操作:
方式一: 使用<map>及<entry>标签为key和value赋值,同时也用到了外部引用(value-ref)
<bean id="student9" class="com.atguigu.spring.pojo.Student">
<property name="id" value="1009"/>
<property name="name" value="赵穷"/>
<property name="gender" value="女"/>
<property name="age" value="34"/>
<property name="hobby" >
<array>
<value>抽烟</value>
<value>喝酒</value>
</array>
</property>
<property name="teacherMap">
<map>
<entry key="10010" value-ref="teacher1"/>
<entry key="10086" value-ref="teacher2"/>
</map>
</property>
</bean>
<!--外部bean:-->
<bean id="teacher1" class="com.atguigu.spring.pojo.Teacher">
<property name="tId" value="10010"/>
<property name="tName" value="联通"/>
</bean>
<bean id="teacher2" class="com.atguigu.spring.pojo.Teacher">
<property name="tId" value="10086"/>
<property name="tName" value="移动"/>
</bean>
对<entry>的说明:
方式二:使用<\util:map>为集合中的键值对进行赋值,过程类似于<\util:list>
<bean id="student10" class="com.atguigu.spring.pojo.Student">
<property name="id" value="1010"/>
<property name="name" value="赵负"/>
<property name="gender" value="女"/>
<property name="age" value="34"/>
<property name="hobby" >
<array>
<value>抽大烟</value>
<value>喝白酒</value>
</array>
</property>
<property name="teacherMap" ref="teacherMap"/>
</bean>
<util:map id="teacherMap">
<entry key="10010" value-ref="teacher1"/>
<entry key="10086" value-ref="teacher2"/>
</util:map>
引入p命名空间后,可以通过以下方式为bean的各个属性赋值(xmlns:p="http://www.springframework.org/schema/p")
<bean id="student11" class="com.atguigu.spring.pojo.Student"
p:id="1011" p:age="12" p:name="丽丽" p:teacherMap-ref="teacherMap"/>
<!-- 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>
<!-- 引入外部属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<?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">
<!--引入jdbc.properties,之后可以通过${key}-value的方式进行访问-->
<context:property-placeholder location="jdbc.properties"></context:property-placeholder>
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>
在Spring中可以通过配置bean标签的scope属性来指定bean的作用域范围:
scope="singleton":表示获取该bean所对应的对象都是同一个(单例)
scope="prototype":表示获取该bean所对应的对象都不是同一个(多例)
配置bean:
<!-- scope属性:取值singleton(默认值),bean在IOC容器中只有一个实例,IOC容器初始化时创建
对象 -->
<!-- scope属性:取值prototype,bean在IOC容器中可以有多个实例,getBean()时创建对象 -->
<bean class="com.atguigu.bean.User" scope="prototype"></bean>
bean的后置处理器:
bean的后置处理器会在生命周期的初始化前后添加额外的操作,需要实现BeanPostProcessor接口,且配置到IOC容器中,需要注意的是,bean后置处理器不是单独针对某一个bean生效,而是针对IOC容器中所有bean都会执行
创建bean的后置处理器:
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
//此方法在bean的生命周期初始化之前执行
System.out.println("后置处理器的postProcessBeforeInitialization");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// 此方法在bean的生命周期初始化之后再执行
System.out.println("后置处理器的postProcessAfterInitialization");
return bean;
}
}
配置bean:
<!-- bean的后置处理器要放入IOC容器才能生效 -->
<bean id="myBeanProcessor" class="com.atguigu.spring.process.MyBeanProcessor"/>
简介: FactoryBean是Spring提供的一种整合第三方框架的常用机制。和普通的bean不同,配置一个FactoryBean类型的bean,在获取bean的时候得到的并不是class属性中配置的这个类的对象,而是getObject()方法的返回值。通过这种机制,Spring可以帮我们把复杂组件创建的详细过程和繁琐细节都屏蔽起来,只把最简洁的使用界面展示给我们。
FactoryBean是一个接口,需要创建一个类实现该接口
其中有三个方法:
当把FactoryBean的实现类配置为bean时,会将当前类中的getObject()所返回的对象交给ioc容器管理
操作: 1.创建类UserFactoryBean
public class UserFactoryBean implements FactoryBean<User> {
@Override
public User getObject() throws Exception {
return new User();
}
@Override
public Class<?> getObjectType() {
return User.class;
}
}
2.配置bean:
<bean id="user" class="com.atguigu.bean.UserFactoryBean"></bean>
3.测试类:
@Test
public void testFactoryBean(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-factory.xml");
User user = ioc.getBean(User.class);
System.out.println(user);
}
自动装配: 根据指定的策略,在ioc容器中匹配某个bean,自动为bean中的类类型的属性或接口类型的属性赋值
可以通过bean标签中的autowire属性设置自动装配的策略
自动装配的策略: no,default:表示不装配,即bean中的属性不会自动匹配某个bean为属性赋值,此时属性使用默认值
byType:根据要赋值的属性的类型,在ioc容器中匹配某个bean,为属性赋值
注意:
1.若通过类型没有找到任何一个类型匹配的bean,此时不装配,属性使用默认值
2.若通过类型找到了多个类型匹配的bean,此时会抛出异常
byName:根据要赋值的属性的属性名作为bean的id在ioc容器中匹配某个bean,为属性赋值
前提:
创建类UserController:
public class UserController {
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public void saveUser(){
userService.saveUser();
}
}
创建接口UserService:
public interface UserService {
void saveUser();
}
创建类UserServiceImpl实现接口UserService:
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void saveUser() {
userDao.saveUser();
}
}
创建接口UserDao:
public interface UserDao {
void saveUser();
}
创建类UserDaoImpl实现接口UserDao:
public class UserDaoImpl implements UserDao {
@Override
public void saveUser() {
System.out.println("保存成功");
}
}
操作:
1.配置bean:
使用bean标签的autowire属性设置自动装配效果
自动装配方式:byType
byType:根据类型匹配IOC容器中的某个兼容类型的bean,为属性自动赋值
若在IOC中,没有任何一个兼容类型的bean能够为属性赋值,则该属性不装配,即值为默认值null
若在IOC中,有多个兼容类型的bean能够为属性赋值,则抛出异常NoUniqueBeanDefinitionException
<bean id="userController"class="com.atguigu.autowire.xml.controller.UserController" autowire="byType"></bean>
<bean id="userService" class="com.atguigu.autowire.xml.service.impl.UserServiceImpl" autowire="byType"></bean>
<bean id="userDao" class="com.atguigu.autowire.xml.dao.impl.UserDaoImpl"></bean>
总结:当使用byType实现自动装配时,ioc容器中有且只有一个类型匹配的bean能够为属性赋值
自动装配方式:byName
byName:将自动装配的属性的属性名,作为bean的id在IOC容器中匹配相对应的bean进行赋值
<bean id="userController" class="com.atguigu.autowire.xml.controller.UserController" autowire="byName"></bean>
<bean id="userService" class="com.atguigu.autowire.xml.service.impl.UserServiceImpl" autowire="byName"></bean>
<bean id="userServiceImpl" class="com.atguigu.autowire.xml.service.impl.UserServiceImpl" autowire="byName"></bean>
<bean id="userDao" class="com.atguigu。autowire.xml.dao.impl.UserDaoImpl"></bean>
<bean id="userDaoImpl" class="com.atguigu.autowire.xml.dao.impl.UserDaoImpl"></bean>
总结:当类型匹配的bean有多个时,此时可以使用byName实现自动装配
3.测试类:
@Test
public void testAutoWireByXML(){
ApplicationContext ac = new ClassPathXmlApplicationContex ("autowire-xml.xml");
UserController userController = ac.getBean(UserController.class);
userController.saveUser();
}
本文章使用limfx的vscode插件快速发布