第二章 IOC(控制反转)
2.1什么是IOC
控制反转(IoC,Inversion of Control),是一个概念,是一种思想。指将传统上由程序代码直接操控的对象调用权交给容器,通过容器来实现对象的装配和管理。控制反转就是对对象控制权的转移,从程序代码本身反转到了外部容器。通过容器实现对象的创建,属性赋值,依赖的管理。
IoC 是一个概念,是一种思想,其实现方式多种多样。当前比较流行的实现方式是依赖注入
依赖:classA 类中含有 classB 的实例,在 classA 中调用 classB 的方法完成功能,即 classA 对 classB 有依赖。
➢ 依赖注入:DI(Dependency Injection),程序代码不做定位查询,这些工作由容器自行 完成。
依赖注入 DI 是指程序运行过程中,若需要调用另一个对象协助时,无须在代码中创建被调用者,而是依赖于外部容器,由外部容器创建后传递给程序。 Spring 的依赖注入对调用者与被调用者几乎没有任何要求,完全支持对象之间依赖关系 的管理。
Spring 容器是一个超级大工厂,负责创建、管理所有的 Java 对象,这些 Java 对象被称为 Bean。Spring 容器管理着容器中 Bean 之间的依赖关系,Spring 使用“依赖注入”的方式 来管理 Bean 之间的依赖关系。使用 IoC 实现对象之间的解耦和。
2.2 第一个Spring项目
2.2.1 实现步骤
-
创建Maven项目
-
加入Maven依赖–> spring的依赖 junit依赖等
-
创建类(接口和它的实现类)
和没有使用框架一样,就是普通的类
-
创建spring需要使用的配置文件
声明类的信息,这些类是有spring创建和管理的
- 测试spring创建的类
接下来对每一步进行详细说明:
(1) 创建Maven项目
(2)加入Maven依赖 在pom文件中引入spring框架和junit
<dependencies>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!--springFramework-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.20</version>
</dependency>
</dependencies>
(3)创建类(接口和它的实现类)

SomeService接口:
//创建一个包含doSome()方法的接口
public interface SomeService {
void doSome();
}
SomeServiceImpl类实现上述接口:
//实现SomeService接口
public class SomeServiceImpl implements SomeService {
//重写接口中的方法
@Override
public void doSome() {
System.out.println("执行了some方法!");
}
}
(4)创建spring需要使用的配置文件
在resources下新建一个beans.xml文件,文件名可以为任意(但spring官方建议使用application.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 id="SomeServiceImpl" class="com.bjpw.service.impl.SomeServiceImpl"/>
</beans>
**:**用于定义一个实例对象。一个实例对应一个bean元素。
id:该属性是 Bean 实例的唯一标识,程序通过 id 属性访问 Bean,Bean 与 Bean 间的依赖关系也是通过 id 属性关联的。
**class:**指定该 Bean 所属的类,注意这里只能是类,不能是接口。
(5)测试spring创建的类 使用junit,在test对应路径上进行测试

public class MyTest {
//主动创建方式,即不使用控制反转
@Test
public void test01(){
SomeService service = new SomeServiceImpl();
service.doSome();
}
//使用IOC
@Test
public void test02(){
String config = "beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config);
SomeService someServiceImpl = (SomeService) applicationContext.getBean("SomeServiceImpl");
someServiceImpl.doSome();
}
}
至此,你的第一个spring程序已经实现了。快去测试一下吧!
2.2.2 使用Spring创建非自定义的类实例
上述的SomeServiceImpl这个类是由你自己定义并实现的,如果想要用JAVA提供给我们的一些工具类,能不能也使用Spring来创建呢? ----> 当然是可以的!下面就以java.util中的Date类举例,如何使用spring来创建非自定义的类实例
(1)在配置文件 标签中加入Date类的定义
对beans.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 id="SomeServiceImpl" class="com.bjpw.service.impl.SomeServiceImpl"/>
<!-- ============== 非自定义的bean ============-->
<bean id="mydate" class="java.util.Date"/>
</beans>
(2)在测试类中获取这个Date类
@Test
public void testDate(){
String config = "beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config);
Date mydate = (Date) applicationContext.getBean("mydate");
System.out.println("Date:" + mydate);
}
至此,spring完成了对非自定义类的创建。可以对比看出:spring对自定义类和非自定义都能进行创建,没有什么太大的区别
2.2.3 spring怎么对一个类创建多个实例?
在spring中,可以通过标签中的id不同,来区分不同的实例,例如:想要在程序中创建两个SomeServiceImpl实例
(1)对beans.xml文件进行修改,使用id进行区分
<?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不同-->
<bean id="SomeServiceImpl1" class="com.bjpw.service.impl.SomeServiceImpl"/>
<bean id="SomeServiceImpl2" class="com.bjpw.service.impl.SomeServiceImpl"/>
</beans>
(2)测试
@Test
public void testMoreInstance() {
String config = "beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config);
SomeService someServiceImpl1 = (SomeService) applicationContext.getBean("SomeServiceImpl1");
SomeService someServiceImpl2 = (SomeService) applicationContext.getBean("SomeServiceImpl2");
System.out.println(someServiceImpl == someServiceImpl1);
}
结果显示是:false,说明spring确实创建了两个实例
2.2.4 spirng中bean是何时由容器创建的?
spring中的bean是在 ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config) 代码执行后创建的,如下进行验证:
(1)在SomeServiceImpl中创建一个无参构造方法
public class SomeServiceImpl implements SomeService {
@Override
public void doSome() {
System.out.println("执行了some方法!");
}
//无参构造方法
public SomeServiceImpl() {
System.out.println("SomeServiceImpl的无参数构造方法");
}
}
(2)在测试类中前后加入提示语句,观察构造函数何时调用,即何时创建bean
@Test
public void test(){
String config = "beans.xml";
System.out.println("准备读取xml");
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config);
System.out.println("准备获取bean");
SomeService someServiceImpl = (SomeService) applicationContext.getBean("SomeServiceImpl");
someServiceImpl.doSome();
}
结果:bean是在获取上下文后创建的

2.2.5 怎么获取容器中的bean和bean数量
ApplicationContext中的**getBeanDefinitionNames()方法和getBeanDefinitionCount()**方法
@Test
public void testGet(){
String config = "beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config);
int beanDefinitionCount = applicationContext.getBeanDefinitionCount();
System.out.println("容器中定义的对象数量: "+ beanDefinitionCount);
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
for(String name:beanDefinitionNames){
System.out.println(name);
}
}
结果:
2.3 依赖注入1:基于XML的依赖注入
2.3.1 注入分类
- set注入
- 构造注入
2.3.2 set注入
set 注入也叫设值注入是指:通过 setter 方法传入被调用者的实例。这种注入方式简单、 直观,因而在 Spring 的依赖注入中大量使用。
2.3.2.1 简单数据类型
spring中认为基本数据类型和String都是简单数据类型。对于简单数据类型,set注入步骤:
(1)建立一个基本的类,类中需要实现set方法
public class Student {
//名字
private String name;
//年龄
private int age;
//name的set方法
public void setName(String name) {
System.out.println("用来验证是否调用了setName方法");
this.name = name;
}
//age的set方法
public void setAge(int age) {
System.out.println("用来验证是否调用了setAge方法");
this.age = age;
}
//设置一个类中没有对应属性的set方法,观察是否能够调用。
public void setEmail(String email){
System.out.println("setEmail = " + email);
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
(2)在resouorces中新建一个applicationContext.xml配置文件, 值得注意的是类中并没有email属性,但是有setEmail方法,观察是否会调用setEmail方法
<?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">
<!--
使用set注入=======>(1)简单类型
-->
<!--对于自定义类set注入-->
<bean id="myStudent" class="com.bjpo.ba01.Student">
<property name="age" value="19"/>
<property name="name" value="小明"/>
<property name="email" value="qq邮件"/> <!--类中没有email属性,但是有setEmail方法-->
</bean>
<!--非自定义类注入--> <!--还是调用set方法-->
<bean id="myDate" class="java.util.Date">
<property name="time" value="100000"/> <!--调用setTime方法-->
</bean>
</beans>
(3)测试
@Test
public void test01(){
String config = "ba01/applicationContext.xml"; //读取配置文件
ApplicationContext application = new ClassPathXmlApplicationContext(config); //获取应用上下文
Student myStudent = (Student) application.getBean("myStudent"); //获取自定义类的实例
System.out.println("student对象= " + myStudent);
Date myDate = (Date) application.getBean("myDate"); //获取非自定义类的实例
System.out.println("myData : " + myDate);
}
结果:

看到类已被成功注入,类中并没有email属性,但是还调用了setEmail()这个方法。 因此,对于set注入方式,spring通过配置文件找到的是类中对应的set方法,并不会关心这个属性在类中是否定义。
2.3.2.2 引用类型
当指定 bean 的某属性值为另一 bean 的实例时,通过 ref 指定它们间的引用关系,ref 的值必须为某 bean 的 id 值。
(1)创建一个引用其它类的类
首先先定义一个school类
@Data
@ToString
public class School {
private String name;
private String address;
}
再定义一个student类,包含school属性
package com.bjpo.ba02;
public class Student {
private String name;
private int age;
//声明一个引用数据类型
private School school;
public School getSchool() {
return school;
}
public void setSchool(School school) {
this.school = school;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", school=" + school +
'}';
}
}
(2)在applicationContext.xml文件中进行配置
<!--(2) 引用赋值-->
<!--school实例-->
<bean id="school" class="com.bjpo.ba02.School">
<property name="name" value="蓝天花花幼儿园"/>
<property name="address" value="小猪窝"/>
</bean>
<bean id="refStudent" class="com.bjpo.ba02.Student">
<property name="name" value="张三"/>
<property name="age" value="25"/>
<property name="school" ref="school"/> <!--使用ref 注入school-->
</bean>
(3)测试
@Test
public void test02(){
String config = "ba02/applicationContext.xml";
ApplicationContext application = new ClassPathXmlApplicationContext(config);
Student myStudent = (Student) application.getBean("refStudent");
System.out.println("带引用的student对象 :" + myStudent);
}
结果:

2.3.2 构造注入
构造注入是指,**在构造调用者实例的同时,完成被调用者的实例化。**即,使用构造器设置依赖关系。使用 标签
(1)在类中定义有参数构造方法,删除setter方法
package com.bjpo.ba03;
public class Student {
private String name;
private int age;
//声明一个引用数据类型
private School school;
//无参构造方法
public Student() {
System.out.println("spring使用无参构造方法创建对象");
}
//有参构造方法
public Student(String name, int age, School school) {
System.out.println("spring使用有参构造方法创建对象");
this.name = name;
this.age = age;
this.school = school;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", school=" + school +
'}';
}
}
(2)对配置文件进行修改,使用标签 标签中的name 和 index均可指定参数,但是name方法更直观,使用name更多
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--使用构造注入-->
<!-- 使用name设置-->
<bean id="myStudent" class="com.bjpo.ba03.Student">
<constructor-arg name="name" value="李四"/>
<constructor-arg name="age" value="21"/>
<constructor-arg name="school" ref="school"/>
</bean>
<!-- 使用index方式,根据构造函数的参数位置-->
<bean id="myStudent2" class="com.bjpo.ba03.Student">
<constructor-arg index="0" value="王五"/>
<constructor-arg index="1" value="22"/>
<constructor-arg index="2" ref="school"/>
</bean>
<!-- 省略index位置,严格按照构造参数位置-->
<bean id="myStudent3" class="com.bjpo.ba03.Student">
<constructor-arg value="孙六"/>
<constructor-arg value="23"/>
<constructor-arg ref="school"/>
</bean>
<bean id="school" class="com.bjpo.ba03.School">
<property name="name" value="河南大学"/>
<property name="address" value="河南"/>
</bean>
<!--构造注入创建文件对象-->
<!--创建File 使用构造注入-->
<bean id="myfile" class="java.io.File">
<constructor-arg name="parent" value="/Users/shentao/Documents/JavaCode/JavaCodePra/test/spring" />
<constructor-arg name="child" value="hello.txt"/>
</bean>
</beans>
(3)测试
@Test
public void test01(){
String config = "ba03/applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config);
Student myStudent = (Student) applicationContext.getBean("myStudent");
System.out.println(myStudent.toString());
}
//测试index方式
@Test
public void test02(){
String config = "ba03/applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config);
Student myStudent = (Student) applicationContext.getBean("myStudent2");
System.out.println(myStudent.toString());
}
//测试无index方式
@Test
public void test03(){
String config = "ba03/applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config);
Student myStudent = (Student) applicationContext.getBean("myStudent3");
System.out.println(myStudent.toString());
}
//测试使用构造器注入,获取文件方式
@Test
public void test04(){
String config = "ba03/applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config);
File myFile = (File) applicationContext.getBean("myfile");
System.out.println("myFile = " + myFile.getName());
}
2.3.3 引用类型自动注入
对于引用类型属性的注入,也可不在配置文件中显示的注入。可以通过为标签 设置 autowire 属性值,为引用类型属性进行隐式自动注入(默认是不自动注入引用类型属性)
根据自动注入判断标准的不同,可以分为两种:
-
byName:根据名称自动注入
-
byType: 根据类型自动注入
2.3.3.1 byName方式自动注入
当配置文件中被调用者 bean 的 id 值与代码中调用者 bean 类的属性名相同时,可使用 byName 方式,让容器自动将被调用者 bean 注入给调用者 bean。
语法:
<bean id = ""xx" class = "yyy' autowire="byName">
简单数据类型赋值
</bean>
容器是通过调用者的 bean 类的属性名与配置文件的被调用者 bean 的 id 进行比较而实现自动注入的。值得注意的是,这个byName是区分大小写的


具体步骤:
(1)定义School类和Student类,Student会调用School,具体代码和前文相同。
(2)修改配置文件
<bean id="school" class="com.bjpo.ba04.School">
<property name="name" value="家里蹲大学"/>
<property name="address" value="坐牢"/>
</bean>
//使用autowire的byName进行自动注入
<bean id="Student" class="com.bjpo.ba04.Student" autowire="byName">
<property name="name" value="张三三"/>
<property name="age" value="25"/>
//使用autowire后即可注释掉 ref这个
<!--<property name="school" ref="school"/>
</bean>
(3) 测试
@Test
public void test(){
String config = "ba04/applicationContext.xml";
ApplicationContext application = new ClassPathXmlApplicationContext(config);
Student myStudent = (Student) application.getBean("Student");
System.out.println("使用自动注入引用的student对象 :" + myStudent);
}
2.3.3.2 byType方式自动注入
按类型注入,java类中引用类型的数据类型和spring容器中(配置文件)的class属性是同源关系的,这样的bean能够赋值给引用类型
同源就是一类的意思:
- java类中引用的数据类型和bean的class值是一样的
- java类中引用的数据类型和bean的class值是父子类关系的, 如果同时存在子类和父类 或者 多个相同类的bean 会报错
- java类中引用的数据类型和bean的class值是接口和实现类的关系
语法:
<bean id = ""xx" class = "yyy' autowire="byType">
简单数据类型赋值
</bean>
2.3.4 为多个应用指定spring配置文件
在实际应用里,随着应用规模的增加,系统中 Bean 数量也大量增加,导致配置文件变得非常庞大、臃肿。为了避免这种情况的产生,提高配置文件的可读性与可维护性,可以将 Spring 配置文件分解成多个配置文件。
包含关系的配置文件:
多个配置文件中有一个总文件,总配置文件将各其它子文件通过引入。在 Java 代码中只需要使用总配置文件对容器进行初始化即可。 举例:

(1)配置文件
spring-school.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">
<!-- school模块所有bean的声明-->
<bean id="mySchool" class="com.bjpo.ba06.School">
<property name="name" value="工业大学"/>
<property name="address" value="哈尔滨"/>
</bean>
</beans>
spring-student.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">
<!-- student模块所有bean的声明-->
<bean id="Student" class="com.bjpo.ba06.Student" autowire="byType">
<property name="name" value="张四"/>
<property name="age" value="27"/>
</bean>
</beans>
总配置文件spring-total.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">
<!--表示主配置文件:包含其他的配置文件的,不定义对象-->
<import resource="classpath:ba06/spring-school.xml"/>
<import resource="classpath:ba06/spring-student.xml"/>
<!--使用通配符,但要确保主配置文件不能加载进来-->
<!--<import resource="classpath:ba06/spring-s*.xml"/>-->
</beans>
(2)测试
@Test
public void test02(){
String config = "ba06/spring-total.xml";
ApplicationContext application = new ClassPathXmlApplicationContext(config);
Student myStudent = (Student) application.getBean("Student");
System.out.println("带引用的student对象 :" + myStudent);
}
2.3 依赖注入2:基于注解的依赖注入
2.3.1 基于注解的依赖注入概括
基于注解的di:通过注解完成java对象创建,属性赋值
使用注解的步骤:
-
加入maven依赖 spring-context 在加入spring-context同时会间接加入spring-aop的依赖,使用注解必须使用spring-aop依赖
-
在类中加入spring的注解(多个不同功能的注解)
-
在spring配置文件中,加入一个组件扫描器的标签,说明注解在你的项目中的位置。
-
用注解创建对象,创建容器ApplicationContext
本节需要学习的注解
1. @Component
2. @Repository
3. @Service
4. @Controller
5. @Value
6. @Autowired
7. @Resource
2.3.2 @Component: 注册Bean的注解
需要在类上使用注解@Component,该注解的 value 属性用于指定该 bean 的 id 值。
@Component: 创建对象的,等同于的功能
- 属性:value 就是对象的名称,也就是bean的id值。value的值是唯一的,创建的对象在整个spring容器就一个
- 位置:在类的上面
举例:
(1)加入依赖
(2)在类中加入spring的注解
//这个注解中value可以省略@Component("myStudent")
//也可以不指定对象名称,由spring提供默认名称 --> 不指定对象名称,id为类名的首字母小写
@Component(value = "myStudent") //这个注解等同于<bean id="myStudent" class="com.st.ba01.Student"/>
public class Student {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
(3)在spring配置文件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"
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">
<!--声明组件扫描器 组件就是java对象 base-package:指定注解在你项目中的包名-->
<!--加入component-scan标签,配置文件的变化:
1.加入一个新的约束文件 https://www.springframework.org/schema/context/spring-context.xsd"
2.给这个新的约束文件起个命名空间的名称
xmlns:context="http://www.springframework.org/schema/context" http://www.springframework.org/schema/
-->
<context:component-scan base-package="com.st.ba01"/> <!--扫描com.st.ba01包下所有的文件-->
</beans>
(4)用注解创建对象,创建容器ApplicationContext
@Test
public void test01(){
String config = "ba01/applicationContext.xml";
ApplicationContext applicationContext= new ClassPathXmlApplicationContext(config);
Student myStudent = (Student) applicationContext.getBean("myStudent");
System.out.println(myStudent.toString());
}
spring中和@Component功能一致,创建对象的注解还有
- **@Repository 😗*放在dao的实现类上面,表示创建dao对象,dao对象是能够访问数据库的
- @Service : 放在service的实现类上面,表示创建service对象,service对象是业务处理,可以有事务等功能
- @Controller : 放在controller的实现类上面,表示创建controller对象,controller能够接收用户提交的参数,显示请求的处理结果
以上是注解使用方法相同和@Component一样,都能创建对象,但是这三个注解还有额外的功能。
注意事项:
- 这个注解中value可以省略 ===> @Component(“myStudent”)
- 这个注解可以不指定对象名称,由spring提供默认名称,bean 的 id 是类名的首字母小写。===> @Component
2.3.3 @Value: 简单类型属性注入
@Value: 简单类型的属性赋值
- 属性:value 是String类型的,表示简单类型的属性值
- 位置:
- 在属性定义的上面,无需set方法,推荐使用
- 在set方法上面
举例:
@Component(value = "myStudent")
public class Student {
// @Value(value = "张飞") //第一种方法
private String name;
// @Value(value = "29")
private int age;
@Value(value = "张飞") //第二种方法
public void setName(String name) {
System.out.println("set方法获取name值:"+name);
this.name = name;
}
@Value(value = "29")
public void setAge(int age) {
System.out.println("set方法获取age值:"+age);
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2.3.4 @Autowired:引用类型数据自动注入
@Autowird: spring框架提供的注解,实现引用类型的赋值, 支持byName byType 默认使用byType方式自动注入
- 属性:required。
true:引用赋值失败,报错,终止执行 false:引用赋值失败,继续执行,引用类型是null一般推荐使用true, 默认也是为true - 位置:
- 在属性定义的上面,无需set方法,推荐使用
- 在set方法上面
2.3.4.1 byType自动注入
直接按照语法即可。
测试如果byName没有找到name怎么办?===> 根据Autowired中required属性进行判断,程序是否继续执行
举例:
@Component(value = "myStudent")
public class Student {
@Value(value = "关羽")
private String name;
@Value(value = "30")
private int age;
@Autowired //使用Autowired进行自动注入
private School school;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", school=" + school +
'}';
}
}
2.3.4.2 byName自动注入
byName方式注入,需要传入name值,但是Autowired注解没有name属性,需要借助另一个 @Qualifier注解,步骤:
- 在属性上边加@Autowired
- 在属性上面加Qualifier(value = “bean的id”):表示使用指定名称的bean完成赋值
举例:
school代码:
@Component(value = "liubeiSchool")
public class School {
@Value("成都大学")
private String name;
@Value("蜀")
private String address;
@Override
public String toString() {
return "School{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.address = address;
}
}
student代码:
@Component(value = "myStudent")
public class Student {
@Value(value = "刘备")
private String name;
@Value(value = "31")
private int age;
@Autowired
@Qualifier(value = "liubeiSchool") //注入id为“liubeiSchool”的bean
private School school;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", school=" + school +
'}';
}
}
2.3.5 @Resource:JDK中自带的引用类型数据自动注入注解
@Resource: jdk的注解,支持byName byType,默认为byName,先使用byName自动注入,如果赋值失败,再使用byType
- 属性:value 是String类型的,value属性指定后变成单byName方法,找不到也不再进行byType方法。
- 位置:
- 在属性定义的上面,无需set方法,推荐使用
- 在set方法上面
举例:
不指定value:
@Component(value = "myStudent")
public class Student {
@Value(value = "曹操")
private String name;
@Value(value = "33")
private int age;
@Resource //name不匹配,会使用byType
private School school;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", school=" + school +
'}';
}
}
指定value:
@Component(value = "myStudent")
public class Student {
@Value(value = "曹操")
private String name;
@Value(value = "33")
private int age;
@Resource(name = "CcSchool") //此时如果name不匹配,则不会使用byType了
private School school;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", school=" + school +
'}';
}
}
2.3.6 XML和注解对比
XML 方式优点是:
-
配置和代码是分离的
-
在 xml 中做修改,无需编译代码,只需重启服务器即可将新的配置加载。
xml 的缺点是:编写麻烦,效率低,大型项目过于复杂。
注解优点是:
-
方便
-
直观
-
高效(代码少,没有配置文件的书写那么复杂)。
其弊端也显而易见:以硬编码的方式写入到 Java 代码中,修改是需要重新编译代码的。
总结:需要经常改动的使用xml, 不需要经常改动的使用注解
870




被折叠的 条评论
为什么被折叠?



