ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Spring5学习总结(一)IoC底层原理/工厂模式/创建对象/注入属性/依赖注入/IoC和DI的区别/基于XML实现Bean管理/Bean的生命周期/基于注解实现Bean管理/完全注解开发

2021-08-04 19:02:19  阅读:382  来源: 互联网

标签:配置文件 Bean class bean context import 注解 IoC public


一、概述

  • Spring 是轻量级开源的 JavaEE 框架
  • Spring 可以解决企业应用开发的复杂性
  • Spring 有两个核心部分:IoCAOP
    (1)IoC:(Inversion of Control) 指控制反转或反向控制。在Spring框架中我们通过配置创建类对象,由Spring在运行阶段实例化、组装对象。(把创建对象过程交给 Spring 进行管理)
    (2)AOP:(Aspect Oriented Programming)面向切面编程,其思想是在执行某些代码前执行另外的代码,使程序更灵活、扩展性更好,可以随便地添加、删除某些功能。Servlet中的Filter便是一种AOP思想的实现
  • Spring 特点
    (1)方便解耦,简化开发
    (2)AOP 编程支持
    (3)方便程序测试
    (4)方便和其他框架进行整合
    (5)方便进行事务操作
    (6)降低 API 开发难度

二、入门案例

  1. 下载 Spring5
    在这里插入图片描述

  2. 打开 idea 工具,创建普通 Java 工程

  3. 导入 Spring5 相关 jar 包,并添加依赖
    Spring核心容器:在这里插入图片描述
    因此我们需要导入上面四个包,另外我们还需要一个管理日志的包commons-logging.jar在这里插入图片描述
    建一个lib目录,复制jar包进来——>FILE——>Project Structure——>Modules——>Dependencies——>"+"——>JARs or directories——>添加需要的jar包依赖
    在这里插入图片描述

  4. 创建普通类,在这个类创建普通方法

public class User {
    public void hello(){
        System.out.println("hello world");
    }
}
  1. 创建 Spring 配置文件,在配置文件配置创建的对象
    Spring 配置文件使用 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">
    <!--配置User对象创建-->
    <!--id:唯一标识(别名) class:全类名-->
    <bean id="user" class="com.fox.bean.User"></bean>
</beans>
  1. 进行测试代码编写
import com.fox.bean.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //1 加载 spring 配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //2 获取配置创建的对象
        User user = context.getBean("user", User.class);
        System.out.println(user);
        user.hello();
    }
}

在这里插入图片描述

三、IoC详解

(一)概念和原理

1.什么是IoC

  • IoC(Inversion of Control) 指控制反转或反向控制。在Spring框架中我们通过配置创建类对象,由Spring在运行阶段实例化、组装对象。(把创建对象过程交给 Spring 进行管理)
  • 使用 IoC 目的:为了降低耦合度
  • 什么是反转
    反转是相对于正向而言的,那么什么算是正向的呢?考虑一下常规情况下的应用程序,如果要在A里面使用C的方法,你会怎么做呢?当然是直接去创建C的对象,也就是说,是在A类中主动去获取所需要的外部资源C,这种情况被称为正向的。那么什么是反向呢?就是A类不再主动去获取C,而是被动等待,等待IoC的容器获取一个C的实例,然后反向的注入到A类中。

2.IoC底层原理

IoC是通过xml解析、工厂模式、反射共同实现的

(1)什么是工厂模式

该模式用于封装和管理对象的创建,是一种创建型模式。工厂模式的本质就是用工厂方法代替new操作创建一种实例化对象的方式。工厂模式可以降低耦合度。一句话中总结就是方便创建同种类型接口产品的复杂对象
案例
假如我们需要在一个类的方法中调用另一个类的方法,那么原始方式如下:
在这里插入图片描述
我们会发现,这样的方式,两个类的耦合度十分高,那么我们可以利用工厂模式进行优化:
在这里插入图片描述
耦合度是不能完全消除的,只能最大限度降低耦合度

(2)理解IoC底层原理

举个不恰当的例子:就像找女朋友,如果我们自己找,就要想办法认识她们,投其所好送其所要,我们必须自己设计和面对每个环节,充满了耦合;而IoC就类似婚介帮我们找女朋友,婚介会按照我们的要求,提供一个女生,我们只需要去和她谈恋爱、结婚就行了。
在这里插入图片描述

(二) IoC 容器两种接口

IoC 思想基于 IoC 容器完成,IoC 容器底层就是对象工厂

Spring 提供了 IoC 容器两种实现方式:(两种接口)
(1)BeanFactory:IoC 容器基本实现,是 Spring 内部的使用接口,不提供开发人员进行使用

//加载 spring 配置文件
BeanFactory context = new ClassPathXmlApplicationContext("bean1.xml");

(2)ApplicationContext:BeanFactory 接口的子接口,提供更多更强大的功能,一般由开发人
员进行使用

//加载 spring 配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

BeanFactory和ApplicationContext最大的区别

  • 用BeanFactory加载配置文件时候不会创建对象,在获取(使用)对象时才去创建对象
  • 用ApplicationContext加载配置文件时候就会把在配置文件的对象进行创建
  • 你可能会觉得要用时才创建的Beanfactory节省资源,但是还是推荐ApplicationContext,因为它可以在Tomcat服务器启动时(最耗时耗资源的阶段)把创建对象的工作给一并解决

ApplicationContext 接口有两个常用的实现类
在这里插入图片描述
如果你的xml配置文件是在本地某盘符下,就可以用FileSystemXmlApplicationContext加载配置文件,而如果你的xml配置文件就在本项目的src下,就可以用ClassPathXmlApplicationContext加载配置文件。

(三)Bean管理

1.什么是 Bean 管理

  • Bean 管理指的是两个操作
    • Spring 创建对象
    • Spirng 注入属性
  • Bean 管理操作有两种方式:
    • 基于 xml 配置文件方式实现
    • 基于注解方式实现

2.基于xml配置文件方式实现Bean管理

(1)创建对象

<bean id="user" class="com.fox.bean.User"></bean>
  • 在 spring 配置文件中,使用 bean 标签,标签里面添加对应属性,就可以实现对象创建
  • 在 bean 标签中有很多属性,其中常用的属性:
    • id 属性:唯一标识(别名)
    • class 属性:类全路径
    • name属性:类似id属性,但它可以包含特殊字符如“/”(name属性是早期为Structs1使用的,现在用得少)
  • 创建对象时候,默认也是执行无参构造方法完成对象创建

(2)注入属性

在讲注入属性前,我们要先了解一个概念:DI(Dependency Injection),依赖注入

①什么是DI(依赖注入)
  • 是指spring框架在创建bean对象时,动态的将依赖对象注入到bean组件中。组件之间依赖关系由容器在运行期决定,形象的说,依赖注入即由容器动态地将某个依赖关系注入到组件之中。通过依赖注入机制,我们只需要通过简单的配置,而无需任何代码就可指定目标需要的资源,完成自身的业务逻辑,而不需要关心具体的资源来自何处,由谁实现。
  • 理解DI的关键是:“谁依赖谁,为什么需要依赖,谁注入谁,注入了什么”,那我们来深入分析一下:
    • 谁依赖于谁:当然是对象依赖于IoC容器;
    • 为什么需要依赖:对象需要IoC容器来提供对象需要的外部资源;
    • 谁注入谁:很明显是IoC容器注入应用程序某个对象
    • 注入了什么:就是注入某个对象所需要的外部资源(包括对象、资源、常量数据)。
②IoC和DI的区别:
  • 控制反转就是对对象控制权的转移,从程序代码本身反转到了外部容器。把对象的创建、初始化、销毁等工作交给spring容器来做。由spring容器控制对象的生命周期。即是将new 的过程交给spring容器去处理;
    DI依赖注入是指程序运行过程中,若需要调用另一个对象协助时,无须在代码中创建被调用者,而是依赖于外部容器,由外部容器创建后传递给程序。依赖注入是目前最优秀的解耦方式。依赖注入让Spring的Bean之间以配置文件的方式组织在一起,而不是以硬编码的方式耦合在一起的。
  • DI是IoC中一种具体实现,DI的实现依赖于IoC,先有控制反转才有依赖注入(依赖注入需要在创建对象的基础上才能进行)。相对IoC 而言,“依赖注入”明确描述了“被注入对象依赖IoC容器配置依赖对象”。
  • IoC模式太普遍,任何框架都是IoC,为了让表意更明确,决定用DI来精确指称这个模式。
    举个不恰当的例子:
    IoC ioc = the_pattern;
    DI di = (DI)ioc;
    显然,说the_pattern是IoC或DI都行。但严格说IoC.class == DI.class肯定不为真,两者还是有区别,是 is a 的关系。
③第一种注入属性方式:使用 set 方法进行注入

1、创建类,定义属性和对应的 set 方法

public class Book {
    //创建属性
    private String bname;
    private String bauthor;
    //创建属性对应的 set 方法
    public void setBname(String bname) {
   	    this.bname = bname;
 	}
 	public void setBauthor(String bauthor) {
	    this.bauthor = bauthor;
 	} 
 	@Override
    public String toString() {
        return "Book{" +
                "bname='" + bname + '\'' +
                ", bauthor='" + bauthor + '\'' +
                '}';
    }
}

2、在 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 id="book" class="com.fox.bean.Book">
	 <!--使用 property 完成属性注入
	 name:类里面属性名称
	 value:向属性注入的值
	 -->
		<property name="bname" value="Java从入门到放弃"></property>
		<property name="bauthor" value="小明"></property>
	</bean>
</beans>

3、测试类

import com.fox.bean.Book;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //1 加载 spring 配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //2 获取配置创建的对象
        Book book = context.getBean("book", Book.class);
        System.out.println(book);
    }
}

在这里插入图片描述

④第二种注入属性方式:使用有参数构造进行注入

1、创建类,定义属性,创建属性对应的有参构造方法

public class Book {
    //创建属性
    private String bname;
    private String bauthor;
    //创建属性对应的有参构造方法
    public Book(String bname,String bauthor){
        this.bname=bname;
        this.bauthor=bauthor;
    }
    @Override
    public String toString() {
        return "Book{" +
                "bname='" + bname + '\'' +
                ", bauthor='" + bauthor + '\'' +
                '}';
    }
}

2、在 spring 配置文件中进行配置
配置了constructor-arg组件以后,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 id="book" class="com.fox.bean.Book">
     	<constructor-arg name="bname" value="Java从入门到放弃"></constructor-arg>
     	<constructor-arg name="bauthor" value="小明"></constructor-arg>
<!--        也可以用index取代name,index="0"代表此类的第一个属性,以此类推:-->
<!--        <constructor-arg index="0" value="Java从入门到放弃"></constructor-arg>-->
<!--        <constructor-arg index="1" value="小明"></constructor-arg>-->
	</bean>
</beans>

3、测试类

import com.fox.bean.Book;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //1 加载 spring 配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //2 获取配置创建的对象
        Book book = context.getBean("book", Book.class);
        System.out.println(book);
    }
}

在这里插入图片描述

⑤p名称空间注入(了解)

这个其实也是set方法进行注入的一种简化形式

1、创建类,定义属性和对应的 set 方法

public class Book {
    //创建属性
    private String bname;
    private String bauthor;
    //创建属性对应的 set 方法
    public void setBname(String bname) {
   	    this.bname = bname;
 	}
 	public void setBauthor(String bauthor) {
	    this.bauthor = bauthor;
 	} 
 	@Override
    public String toString() {
        return "Book{" +
                "bname='" + bname + '\'' +
                ", bauthor='" + bauthor + '\'' +
                '}';
    }
}

2、我们需要添加 p 名称空间到配置文件中

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="book" class="com.fox.bean.Book" p:bname="Java从入门到放弃" p:bauthor="小明">
    </bean>
</beans>

3、测试类

import com.fox.bean.Book;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //1 加载 spring 配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //2 获取配置创建的对象
        Book book = context.getBean("book", Book.class);
        System.out.println(book);
    }
}

在这里插入图片描述

⑥xml 注入其他类型属性
Ⅰ.注入字面量

1)注入null值:

<?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="book" class="com.fox.bean.Book">
        <property name="bname" value="Java从入门到放弃"></property>
        <!--给属性设置空值-->
        <property name="bauthor">
            <null/>
        </property>
    </bean>
</beans>

在这里插入图片描述

2)注入包含特殊符号的属性值:
需求:书名需要添加<<>>这个特殊符号

  • 方式一,利用转义字符:
<?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="book" class="com.fox.bean.Book">
		<property name="bname" value="&lt;&lt;Java从入门到放弃&gt;&gt;"></property>
        <property name="bauthor" value="小明"></property>
    </bean>
</beans>

在这里插入图片描述

<?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="book" class="com.fox.bean.Book">
        <property name="bname">
            <value><![CDATA[<<Java从入门到放弃>>]]></value>
        </property>
        <property name="bauthor" value="小明"></property>
    </bean>
</beans>

在这里插入图片描述

Ⅱ.注入外部bean

不光可以注入字符串、基本数据类型的属性,对象也可以注入:
在这里插入图片描述
UserDao:

public interface UserDao {
    public void show();
}

UserDaoImpl:

public class UserDaoImpl implements UserDao {
    @Override
    public void show() {
        System.out.println("这是UserDaoImpl的show方法");
    }
}

UserService:

import com.fox.dao.UserDao;

public class UserService {
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void show(){
        System.out.println("这是UserService的show方法");
        userDao.show();
        //原始方式:(耦合性高)
        //UserDao userDao=new UserDaoImpl();
        //userDao.show();
    }
}

在 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 id="userService" class="com.fox.service.UserService">
        <!--注入的属性是对象
        name属性:类中属性的名称
        ref属性:该对象bean标签的id值
        -->
        <property name="userDao" ref="userDaoImpl"></property>
    </bean>
    <!--外部bean-->
    <bean id="userDaoImpl" class="com.fox.dao.UserDaoImpl"></bean>
</beans>

测试类:

import com.fox.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //1 加载 spring 配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //2 获取配置创建的对象
        UserService userService = context.getBean("userService", UserService.class);
        userService.show();
    }
}

在这里插入图片描述

Ⅲ.注入内部bean

需求:一对多关系:一个部门有多个员工,一个员工属于一个部门

Employee类:

public class Employee {
    private String ename;
    private String id;
    private Department department;

    public void setEname(String ename) {
        this.ename = ename;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "ename='" + ename + '\'' +
                ", id='" + id + '\'' +
                ", department=" + department +
                '}';
    }
}

Department类:

public class Department {
    private String dname;

    public void setDname(String dname) {
        this.dname = dname;
    }

    @Override
    public String toString() {
        return "Department{" +
                "dname='" + dname + '\'' +
                '}';
    }
}

在 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 name="employee" class="com.fox.bean.Employee">
        <property name="ename" value="小明"></property>
        <property name="id" value="1364"></property>
        <property name="department">
            <!--内部bean,设置对象类型属性-->
            <bean name="department" class="com.fox.bean.Department">
                <property name="dname" value="安保部"></property>
            </bean>
        </property>
    </bean>
</beans>

测试类:

import com.fox.bean.Employee;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //1 加载 spring 配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //2 获取配置创建的对象
        Employee employee = context.getBean("employee", Employee.class);
        System.out.println(employee);
    }
}

在这里插入图片描述

Ⅳ.级联赋值

还是以一对多关系作为演示,级联赋值就是在给Employee对象的属性赋值时就同时给Department对象的属性赋值,上面的外部bean、内部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 name="employee" class="com.fox.bean.Employee">
        <property name="ename" value="小明"></property>
        <property name="id" value="1364"></property>
        <property name="department" ref="department"></property>
        <!--级联赋值-->
        <property name="department.dname" value="技术部"></property>
    </bean>

    <bean name="department" class="com.fox.bean.Department">
    </bean>
</beans>

但是要想使用这种方法,我们需要在Employee类中加上一个Getter方法,用于获取department对象:

public Department getDepartment() {
    return department;
}

在这里插入图片描述

Ⅴ.注入数组和集合属性

集合包括:List集合、Set集合、Map集合等
Student类:

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Student {
    //1 数组类型属性
    private String[] courses;
    //2 list集合类型属性
    private List<String> list;
    //3 set集合类型属性
    private Set<String> set;
    //4 map集合类型属性
    private Map<String,String> map;

    public void setCourses(String[] courses) {
        this.courses = courses;
    }
    public void setList(List<String> list) {
        this.list = list;
    }
    public void setSet(Set<String> set) {
        this.set = set;
    }
    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    public void test() {
        System.out.println(Arrays.toString(courses));
        System.out.println(list);
        System.out.println(set);
        System.out.println(map);
    }
}

在 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 id="student" class="com.fox.bean.Student">
        <!--数组类型属性注入-->
        <property name="courses">
            <array>
                <value>语文</value>
                <value>英语</value>
                <value>数学</value>
            </array>
        </property>
        <!--list类型属性注入-->
        <property name="list">
            <list>
                <value>生物</value>
                <value>化学</value>
                <value>物理</value>
            </list>
        </property>
        <!--set类型属性注入-->
        <property name="set">
            <set>
                <value>政治</value>
                <value>历史</value>
                <value>地理</value>
            </set>
        </property>
        <!--map类型属性注入-->
        <property name="map">
            <map>
                <entry key="选修" value="美术"></entry>
                <entry key="体育" value="篮球"></entry>
            </map>
        </property>
    </bean>
</beans>

测试类:

import com.fox.bean.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //1 加载 spring 配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //2 获取配置创建的对象
        Student student = context.getBean("student", Student.class);
        student.test();
    }
}

在这里插入图片描述
假如集合中的数据不是字符串类型而是对象类型呢?
Course类:

public class Course {
    private String cname;

    public void setCname(String cname) {
        this.cname = cname;
    }

    @Override
    public String toString() {
        return "Course{" +
                "cname='" + cname + '\'' +
                '}';
    }
}

Student类:

import java.util.List;

public class Student {
    private List<Course> list;

    public void setList(List<Course> list) {
        this.list = list;
    }

    public void test() {
        System.out.println(list);
    }
}

在 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 id="student" class="com.fox.bean.Student">
        <!--注入list集合类型,值是对象-->
        <property name="list">
            <list>
                <ref bean="course1"></ref>
                <ref bean="course2"></ref>
                <ref bean="course3"></ref>
            </list>
        </property>
    </bean>
    <!--创建多个course对象-->
    <bean id="course1" class="com.fox.bean.Course">
        <property name="cname" value="语文"></property>
    </bean>
    <bean id="course2" class="com.fox.bean.Course">
        <property name="cname" value="数学"></property>
    </bean>
    <bean id="course3" class="com.fox.bean.Course">
        <property name="cname" value="英语"></property>
    </bean>
</beans>

测试类:

import com.fox.bean.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //1 加载 spring 配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //2 获取配置创建的对象
        Student student = context.getBean("student", Student.class);
        student.test();
    }
}

在这里插入图片描述
假如Student类中的某个集合属性和其他类的集合属性一模一样,想再次使用怎么办呢?(把集合注入部分提取出来,以list集合为例)
Student类:

import java.util.List;

public class Student {
    private List<String> list;

    public void setList(List<String> list) {
        this.list = list;
    }

    public void test() {
        System.out.println(list);
    }
}

在 spring 配置文件中引入名称空间 util,并使用 util 标签完成 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: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="courseList">
        <value>语文</value>
        <value>数学</value>
        <value>英语</value>
    </util:list>
    <bean id="student" class="com.fox.bean.Student">
        <property name="list" ref="courseList"></property>
    </bean>
</beans>

测试类:

import com.fox.bean.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //1 加载 spring 配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //2 获取配置创建的对象
        Student student = context.getBean("student", Student.class);
        student.test();
    }
}

在这里插入图片描述

⑦工厂bean
  • Spring 有两种类型 bean:一种普通 bean,另外一种工厂 bean(FactoryBean)
    • 普通 bean:在配置文件中定义的 bean 的 class 属性中的类型就是getBean()方法的返回类型
    • 工厂 bean:在配置文件定义 bean 的 class 属性中的类型可以和getBean()方法的返回类型不一样
  • 工厂bean的创建步骤
    • 第一步:创建类,让这个类实现接口 FactoryBean
    • 第二步:实现接口里面的方法,在实现的getObject()方法中自定义返回的 bean 类型

Person类:

public class Person {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}

自定义工厂bean:

import org.springframework.beans.factory.FactoryBean;

public class MyBean implements FactoryBean<Person> {
    @Override
    public Person getObject() throws Exception {
        Person p = new Person();
        p.setName("小明");
        return p;
    }

    @Override
    public Class<?> getObjectType() {
        return null;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}

在 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 id="myBean" class="com.fox.bean.MyBean">
    </bean>

</beans>

测试类:

import com.fox.bean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //1 加载 spring 配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //2 获取配置创建的对象
        Person p = context.getBean("myBean", Person.class);
        System.out.println(p);
    }
}

在这里插入图片描述
由此我们可以看出,工厂bean在配置文件定义 bean 的 class 属性中的类型可以和getBean()方法的返回类型不一样

⑧bean作用域(scope)
  • 在 Spring 里面,我们可以设置创建的 bean 实例是单实例还是多实例
  • 在 Spring 里面,默认情况下(不进行设置的话),bean 是单实例对象:

Person类:

public class Person {

}

在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 id="person" class="com.fox.bean.Person">
    </bean>

</beans>

测试类:

import com.fox.bean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //1 加载 spring 配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //2 获取配置创建的对象
        Person p1 = context.getBean("person", Person.class);
        Person p2 = context.getBean("person", Person.class);
        System.out.println(p1);
        System.out.println(p2);
    }
}

在这里插入图片描述

Ⅰ.如何设置单实例还是多实例?

在 spring 配置文件 bean 标签里面有个属性(scope)用于设置单实例还是多实例:

  • singleton:默认值,表示是单实例对象
  • prototype:表示是多实例对象
<?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="person" class="com.fox.bean.Person" scope="prototype">
    </bean>

</beans>

在这里插入图片描述

Ⅱ.singleton 和 prototype 的区别
  • singleton 表示单实例,prototype 表示多实例
  • 设置 scope 值是 singleton 时候,加载 spring 配置文件new ClassPathXmlApplicationContext("bean.xml");的时候就会创建单实例对象;设置 scope 值是 prototype 时候,不是在加载 spring 配置文件时候创建 对象,而是在调用getBean()方法时候才创建多实例对象
Ⅲ.scope属性的其他取值

scope属性还可以取值request和session:

  • scope="request"的bean,在每个请求到来时,会创建一个bean实例与当前的请求对应。在不同的页面,这个bean是不同的,也就是说你在不同的页面对同一个ID的bean操作,不会影响到其他页面。(每个request都会重新创建一个bean)
  • scope="session"的bean,会将该实例保存在session中。你在所有页面的bean是同一个,在任意一个页面操作它,在其它页面也能看它改变了。
⑨bean的生命周期
Ⅰ.什么是生命周期

生命周期:从对象创建到对象销毁的过程

Ⅱ.bean的生命周期

①通过构造器创建 bean 实例(调用无参构造)
②为 bean 的属性设置值(调用 set 方法)和对其他 bean 的引用
③调用 bean 的初始化的方法(需要手动进行配置初始化的方法)
④bean 对象被获取(可以使用了)
⑤当容器关闭的时候,调用 bean 的销毁的方法(需要手动进行配置销毁的方法)
案例
Person类:

public class Person {
    public Person(){
        System.out.println("1、执行无参数构造创建 bean 实例");
    }
    private String name;

    public void setName(String name) {
        this.name = name;
        System.out.println("2、调用 set 方法设置属性值");
    }
    public void initMethod(){
        System.out.println("3、执行初始化的方法");
    }
    public void destroyMethod(){
        System.out.println("5、执行销毁的方法");
    }
}

在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 id="person" class="com.fox.bean.Person" init-method="initMethod" destroy-method="destroyMethod">
        <property name="name" value="小明"></property>
    </bean>

</beans>

测试类:

import com.fox.bean.Person;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //1 加载 spring 配置文件
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //2 获取配置创建的对象
        Person p = context.getBean("person", Person.class);
        System.out.println("4、获取创建 bean 实例对象");
        //close()销毁bean实例,会调用到destroyMethod()
        context.close();//此方法ApplicationContext没有,而子类ClassPathXmlApplicationContext才有
    }
}

在这里插入图片描述

Ⅲ.bean的最完整生命周期

如果有 bean 的后置处理器,那么bean 的生命周期应该有七步:

①通过构造器创建 bean 实例(调用无参构造)
②为 bean 的属性设置值(调用 set 方法)和对其他 bean 的引用
③把 bean 实例传递给 bean 后置处理器的方法 postProcessBeforeInitialization()
④调用 bean 的初始化的方法(需要手动进行配置初始化的方法)
⑤把 bean 实例传递给 bean 后置处理器的方法 postProcessAfterInitialization()
⑥bean 对象被获取(可以使用了)
⑦当容器关闭的时候,调用 bean 的销毁的方法(需要手动进行配置销毁的方法)

案例
创建类,实现接口 BeanPostProcessor并重写两个方法,创建后置处理器:

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("3、在初始化之前执行的方法");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("5、在初始化之后执行的方法");
        return bean;
    }
}

Person类:

public class Person {
    public Person(){
        System.out.println("1、执行无参数构造创建 bean 实例");
    }
    private String name;

    public void setName(String name) {
        this.name = name;
        System.out.println("2、调用 set 方法设置属性值");
    }
    public void initMethod(){
        System.out.println("4、执行初始化的方法");
    }
    public void destroyMethod(){
        System.out.println("7、执行销毁的方法");
    }
}

在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 id="person" class="com.fox.bean.Person" init-method="initMethod" destroy-method="destroyMethod">
        <property name="name" value="小明"></property>
    </bean>
    <!--配置后置处理器,这样配置以后会给配置文件中所有的bean加上此后置处理器-->
    <bean id="myBeanPostProcessor" class="com.fox.bean.MyBeanPostProcessor"></bean>

</beans>

测试类:

import com.fox.bean.Person;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //1 加载 spring 配置文件
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //2 获取配置创建的对象
        Person p = context.getBean("person", Person.class);
        System.out.println("6、获取创建 bean 实例对象");
        //close()销毁bean实例,会调用到destroyMethod()
        context.close();//此方法ApplicationContext没有,而子类ClassPathXmlApplicationContext才有
    }
}

在这里插入图片描述

⑩xml自动装配
  • 什么是自动装配?
    根据指定装配规则(属性名称或者属性类型),Spring 自动将匹配的属性值进行注入,只适用于属性是对象类型
  • bean 标签有个 autowire 属性,用于自动装配属性,autowire 属性有两个常用值:
    • byName 根据属性名称注入 ,注入值 bean 的 id 值和类属性名称一样
    • byType 根据属性类型注入,注入值 bean 的 class 值和类属性类型一样

案例
Teacher类:

public class Teacher {
    private String tname;

    public void setTname(String tname) {
        this.tname = tname;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "tname='" + tname + '\'' +
                '}';
    }
}

Student类:

public class Student {
    private String sname;
    private Teacher teacher;

    public void setSname(String sname) {
        this.sname = sname;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sname='" + sname + '\'' +
                ", teacher=" + teacher +
                '}';
    }
}

在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">

    <!--自动装配teacher属性-->
    <bean id="student" class="com.fox.bean.Student" autowire="byName">
    <!--或者写byType,如果使用byType,class为Teacher的bean只能有一个,不然无法识别-->
        <property name="sname" value="小明"></property>
    </bean>

    <bean id="teacher" class="com.fox.bean.Teacher">
        <property name="tname" value="王老师"></property>
    </bean>

</beans>

测试类:

import com.fox.bean.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //1 加载 spring 配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //2 获取配置创建的对象
        Student s = context.getBean("student", Student.class);
        System.out.println(s);
    }
}

在这里插入图片描述

⑪通过外部属性文件注入属性

我们以配置数据库信息为例:

Ⅰ.直接配置数据库连接池信息

(1)导入德鲁伊连接池依赖 jar 包
在这里插入图片描述

(2)配置德鲁伊连接池

<?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">

    <!-- 配置连接池 -->
    <!-- DruidDataSource dataSource = new DruidDataSource(); -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            set方法注入
        -->
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/test"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

</beans>

但是假如这些数据库配置信息将来要修改,还要回头在此配置文件中修改,十分不方便,因此我们可以把这些配置信息写在外部文件中。

Ⅱ.引入外部属性文件配置数据库连接池

(1)创建外部属性文件,properties 格式文件,写数据库信息
jdbc.properties:(src下创建的)

prop.driverClass=com.mysql.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/test
prop.username=root
prop.password=123456

(2)把外部 properties 属性文件引入到 spring 配置文件中

  • 首先引入 context 名称空间
  • 再在 spring 配置文件使用 context 标签引入外部属性文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--引入外部属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 配置连接池 -->
    <!-- DruidDataSource dataSource = new DruidDataSource(); -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            set方法注入
        -->
        <!-- 获取properties文件内容,根据key获取,使用spring表达式获取 -->
        <property name="driverClassName" value="${prop.driverClass}"></property>
        <property name="url" value="${prop.url}"></property>
        <property name="username" value="${prop.username}"></property>
        <property name="password" value="${prop.password}"></property>
    </bean>

</beans>

3.基于注解方式实现Bean管理

在Spring的初始版本中,所有bean都使用XML文件声明。那么在一个稍大的项目中,通常会有上百个组件,如果这些组件都采用XML的bean定义来配置,显然会增加配置文件的体积,查找以及维护起来也不太方便,Spring开发人员很快就意识到这个问题。在之后的版本中,他们提供了基于注解的依赖注入和基于java的配置。

(1)什么是注解

  • 注解是代码特殊标记,格式:@注解名称(属性名称=属性值, 属性名称=属性值...)
  • 使用注解目的:简化 xml 配置

(2)基于注解方式实现创建对象

  • @Service 用来表示一个业务层的bean。
  • @Controller 用来表示一个web控制层的bean,如SpringMvc中的控制器。
  • @Repository 用来表示一个持久层的bean,即数据访问层DAO组件。
  • @Component 当组件不好归类的时候,我们可以使用这个注解进行标注。

上面四个注解功能是一样的,当启用上下文扫描时,它们都可以用来创建 bean 实例,并且提供了与依赖项注入相同的功能。它们唯一的不同之处在于它们的用途,即在Spring MVC中使用@Controller来定义controller。同样,@Service用于在服务层中保存业务逻辑的类,而@Repository用于数据访问层。

案例:基于注解方式实现对象创建

  • 第一步:导入依赖
    在这里插入图片描述
  • 第二步:开启组件扫描,用于扫描指定包下的所有含有以上注解的类
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--上面需要先引入context名称空间-->
    
    <!--开启组件扫描
 		如果想扫描多个包,多个包使用逗号隔开,或者直接扫描上一层目录
	-->
    <context:component-scan base-package="com.fox"></context:component-scan>
    
</beans>
  • 第三步:创建类,在类上面添加创建对象的注解
import org.springframework.stereotype.Service;

//在注解里面 value 属性值可以省略不写
//省略时则默认value值是该类名称首字母小写后的值
//例如:类UserService 省略情况下value值就是:userService
@Service(value = "userService") //此处的value等价于xml文件中bean标签的id属性值
public class UserService {
    public void show(){
        System.out.println("这是UserService的show方法");
    }
}
  • 第四步:测试
import com.fox.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //1 加载 spring 配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //2 获取配置创建的对象
        UserService userService = context.getBean("userService", UserService.class);
        userService.show();
    }
}

在这里插入图片描述
关于组件扫描
组件扫描<context:component-scan></context:component-scan>只扫描@Component,并且一般不会查找@Controller,@Service和@Repository。它们三个之所以能被扫描,是因为它们本身就是用@Component注解的。
我们来看看@Controller,@Service和@Repository注解的源码:

@Component 
public @interface Service { 
....
} 

@Component 
public @interface Repository { 
... 
}

@Component 
public @interface Controller{ 
... 
}

因此,说@Controller、@Service和@Repository是特殊类型的@Component注解并没有错。
如果你定义一个自定义注解并使用@Component注解它,那么它也将使用<context:component-scan></context:component-scan>进行扫描。

组件扫描还有两个细节配置
示例一:只扫描com.fox包下被@Controller注解修饰的类,其他注解修饰的不扫描

<!--
 use-default-filters="false" 表示现在不使用默认 filter,使用自己配置的 filter
 context:include-filter ,设置扫描哪些内容
-->
<context:component-scan base-package="com.fox" use-default-filters="false">
	<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

示例二:com.fox包下被@Controller注解修饰的类不进行扫描

<!--context:exclude-filter: 设置哪些内容不进行扫描-->
<context:component-scan base-package="com.atguigu">
	<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

(3)基于注解方式实现属性注入

① @Autowired:根据属性类型进行自动装配
  • 第一步:通过注解创建对象
public interface UserDao {
    public void show();
}
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
    @Override
    public void show() {
        System.out.println("这是UserDaoImpl的show方法");
    }
}
import org.springframework.stereotype.Service;

@Service
public class UserService {

    public void show(){
        System.out.println("这是UserService的show方法");
    }
}
  • 第二步:开启组件扫描,用于扫描指定包下的所有含有以上注解的类
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--上面需要先引入context名称空间-->
    
    <!--开启组件扫描
 		如果想扫描多个包,多个包使用逗号隔开,或者直接扫描上一层目录
	-->
    <context:component-scan base-package="com.fox"></context:component-scan>
    
</beans>
  • 第三步:在 service 类添加 dao 类型属性,在属性上面使用注解进行注入
import com.fox.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

	//不需要再添加 set 方法
    @Autowired
    private UserDao userDao;

    public void show(){
        System.out.println("这是UserService的show方法");
        userDao.show();
    }
}
  • 第四步:测试
import com.fox.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //1 加载 spring 配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //2 获取配置创建的对象
        UserService userService = context.getBean("userService", UserService.class);
        userService.show();
    }
}

在这里插入图片描述

② @Qualifier:根据名称进行注入

@Qualifier 注解需要和@Autowired 一起使用,其他步骤与上面一样。

import com.fox.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service
public class UserService {

	//不需要再添加 set 方法
    @Autowired
    @Qualifier(value = "userDaoImpl") //根据名称进行注入,此处的value值要与UserDaoImpl类创建对象时注解的value值一致
    private UserDao userDao;

    public void show(){
        System.out.println("这是UserService的show方法");
        userDao.show();
    }
}
③ @Resource:可以根据类型注入,也可以根据名称注入
import com.fox.dao.UserDao;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

@Service
public class UserService {

	//不需要再添加 set 方法
	//@Resource //此时根据类型进行注入
	@Resource(name = "userDaoImpl") //此时根据名称进行注入,此处的name值要与UserDaoImpl类创建对象时注解的value值一致
    private UserDao userDao;

    public void show(){
        System.out.println("这是UserService的show方法");
        userDao.show();
    }
}
④ @Value:注入普通类型属性(上面三个注解只适用于属性是对象类型)
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Value(value = "小明")
    private String name;

    public void show(){
        System.out.println(name);
    }
}

在这里插入图片描述

(4)完全注解开发

上面的例子中依旧还是使用到了xml配置文件,那么可不可以实现完全使用注解进行开发呢。

案例
创建配置类,替代 xml 配置文件:

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration //将此类作为配置类,替代 xml 配置文件
@ComponentScan(basePackages = {"com.fox"})//用于扫描指定包
public class MySpringConfig {
}

编写测试类(注意要使用AnnotationConfigApplicationContext):

import com.fox.config.MySpringConfig;
import com.fox.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //1 加载 spring 配置文件
        ApplicationContext context = new AnnotationConfigApplicationContext(MySpringConfig.class);
        //2 获取配置创建的对象
        UserService userService = context.getBean("userService", UserService.class);
        userService.show();
    }
}

在这里插入图片描述

标签:配置文件,Bean,class,bean,context,import,注解,IoC,public
来源: https://blog.csdn.net/allenfoxxxxx/article/details/119061168

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有