尚硅谷Spring学习笔记(2)-- IOC容器

一、IOC 操作 Bean 管理(FactoryBean)

1、Spring 有两种类型 bean,一种普通 bean,另外一种工厂 bean(FactoryBean)

2、普通 bean:在配置文件中定义 bean 类型就是返回类型

3、工厂 bean:在配置文件定义 bean 类型可以和返回类型不一样

第一步 创建类,让这个类作为工厂 bean,实现接口 FactoryBean
第二步 实现接口里面的方法,在实现的方法中定义返回的 bean 类型

package com.atguigu.spring5.factorybean;

import com.atguigu.spring5.collectiontype.Course;
import org.springframework.beans.factory.FactoryBean;

public class MyBean implements FactoryBean<Course> {

    //定义返回bean
    @Override
    public Course getObject() throws Exception {
        Course course = new Course();
        course.setCname("abc");
        return course;
    }

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

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

bean7.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 id="myBean" class="com.atguigu.spring5.factorybean.MyBean">
    </bean>
</beans>

单元测试

@Test
public void test3() {
    ApplicationContext context =
            new ClassPathXmlApplicationContext("bean7.xml");
    Course course = context.getBean("myBean", Course.class);
    System.out.println(course);
}

在这里插入图片描述

二、IOC 操作 Bean 管理(bean 作用域)

1、在 Spring 里面,设置创建 bean 实例是单实例还是多实例

2、在 Spring 里面,默认情况下,bean 是单实例对象

单实例,表示地址是相同的
在这里插入图片描述
在这里插入图片描述

3、如何设置单实例还是多实例

(1)在 spring 配置文件 bean 标签里面有属性(scope)用于设置单实例还是多实例
(2)scope 属性值
第一个值 默认值,singleton,表示是单实例对象
第二个值 prototype,表示是多实例对象
在这里插入图片描述
在这里插入图片描述
(3)singleton 和 prototype 区别
第一 singleton 单实例,prototype 多实例
第二 设置 scope 值是 singleton 时候,加载 spring 配置文件时候就会创建单实例对象
设置 scope 值是 prototype 时候,不是在加载 spring 配置文件时候创建 对象,在调用
getBean 方法时候创建多实例对象

三、IOC 操作 Bean 管理(bean 生命周期)

1、生命周期

(1)从对象创建到对象销毁的过程

2、bean 生命周期

(1)通过构造器创建 bean 实例(无参数构造)
(2)为 bean 的属性设置值和对其他 bean 引用(调用 set 方法)
(3)调用 bean 的初始化的方法(需要进行配置初始化的方法)
(4)bean 可以使用了(对象获取到了)
(5)当容器关闭时候,调用 bean 的销毁的方法(需要进行配置销毁的方法)

3、演示 bean 生命周期

java类

package com.atguigu.spring5.bean;

public class Orders {

    //无参数构造
    public Orders() {
        System.out.println("第一步 执行无参数构造创建bean实例");
    }

    private String oname;
    public void setOname(String oname) {
        this.oname = oname;
        System.out.println("第二步 调用set方法设置属性值");
    }

    //创建执行的初始化的方法
    public void initMethod() {
        System.out.println("第三步 执行初始化的方法");
    }

    //创建执行的销毁的方法
    public void destroyMethod() {
        System.out.println("第五步 执行销毁的方法");
    }
}

bean8.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 id="orders" class="com.atguigu.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
        <property name="oname" value="手机"></property>
    </bean>
</beans>

单元测试

@Test
public void testBean3() {
    //可以用接口ApplicationContext,也可以用具体实现类ClassPathXmlApplicationContext
//      ApplicationContext context =
//                new ClassPathXmlApplicationContext("bean4.xml");
    ClassPathXmlApplicationContext context =
            new ClassPathXmlApplicationContext("bean8.xml");
    Orders orders = context.getBean("orders", Orders.class);
    System.out.println("第四步 获取创建bean实例对象");
    System.out.println(orders);

    //手动让bean实例销毁
    context.close();
}

在这里插入图片描述

4、bean 的后置处理器,bean 生命周期有七步

(1)通过构造器创建 bean 实例(无参数构造)
(2)为 bean 的属性设置值和对其他 bean 引用(调用 set 方法)
(3)把 bean 实例传递 bean 后置处理器的方法 postProcessBeforeInitialization
(4)调用 bean 的初始化的方法(需要进行配置初始化的方法)
(5)把 bean 实例传递 bean 后置处理器的方法 postProcessAfterInitialization
(6)bean 可以使用了(对象获取到了)
(7)当容器关闭时候,调用 bean 的销毁的方法(需要进行配置销毁的方法)

5、演示添加后置处理器效果

(1)创建类,实现接口 BeanPostProcessor,创建后置处理器

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

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

在这里插入图片描述

四、IOC 操作 Bean 管理(xml 自动装配)

1、什么是自动装配(了解一下即可)

(1)根据指定装配规则(属性名称或者属性类型),Spring 自动将匹配的属性值进行注入

2、演示自动装配过程

(1)根据属性名称自动注入

<!--实现自动装配
 bean 标签属性 autowire,配置自动装配
 autowire 属性常用两个值:
 byName 根据属性名称注入 ,注入值 bean 的 id 值和类属性名称一样
 byType 根据属性类型注入
-->
<bean id="emp" class="com.atguigu.spring5.autowire.Emp" autowire="byName">
 <!--<property name="dept" ref="dept"></property>-->
</bean> 
<bean id="dept" class="com.atguigu.spring5.autowire.Dept"></bean> 

(2)根据属性类型自动注入

<!--实现自动装配
 bean 标签属性 autowire,配置自动装配
 autowire 属性常用两个值:
 byName 根据属性名称注入 ,注入值 bean 的 id 值和类属性名称一样
 byType 根据属性类型注入
-->
<bean id="emp" class="com.atguigu.spring5.autowire.Emp" autowire="byType">
 <!--<property name="dept" ref="dept"></property>-->
</bean> 
<bean id="dept" class="com.atguigu.spring5.autowire.Dept"></bean>

五、IOC 操作 Bean 管理(外部属性文件)

1、直接配置数据库信息

(1)配置德鲁伊连接池
(2)引入德鲁伊连接池依赖 jar 包

在这里插入图片描述

<!--直接配置连接池--> 
<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/userDb"></property>
	 <property name="username" value="root"></property>
	 <property name="password" value="root"></property>
</bean>

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

(1)创建外部属性文件,properties 格式文件,写数据库信息
在这里插入图片描述
(2)把外部 properties 属性文件引入到 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:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       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/util http://www.springframework.org/schema/util/spring-util.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--直接配置连接池-->
    <!--<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/userDb"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>-->

    <!--引入外部属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--配置连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <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>

六、IOC 操作 Bean 管理(基于注解方式)

1、什么是注解

(1)注解是代码特殊标记,格式:@注解名称(属性名称=属性值, 属性名称=属性值…)
(2)使用注解,注解作用在类上面,方法上面,属性上面
(3)使用注解目的:简化 xml 配置

2、Spring 针对 Bean 管理中创建对象提供注解

(1)@Component
(2)@Service
(3)@Controller
(4)@Repository

  • 上面四个注解功能是一样的,都可以用来创建 bean 实例

3、基于注解方式实现对象创建

第一步 引入依赖
在这里插入图片描述
第二步 开启组件扫描

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

    <!--
     开启组件扫描(两种方式)
     1、如果扫描多个包,多个包使用逗号隔开
     2、扫描包上层目录
     -->
    <context:component-scan base-package="com.atguigu"></context:component-scan>
</beans>

第三步 创建类,在类上面添加创建对象注解

//在注解里面value属性值可以省略不写,
//默认值是类名称,首字母小写
//UserService --> userService
@Component(value = "userService")  //等价于<bean id="userService" class=".."/>
@Service
public class UserService {

    public void add() {
        System.out.println("service add.......");
    }
}

在这里插入图片描述

4、开启组件扫描细节配置

<!--
     开启组件扫描(两种方式)
     1、如果扫描多个包,多个包使用逗号隔开
     2、扫描包上层目录
     -->
    <context:component-scan base-package="com.atguigu"></context:component-scan>

    <!--示例1
       use-default-filters="false" 表示现在不使用默认filter,自己配置fillter
       context:include-filter,设置扫描哪些内容
       annotation注解 expression,里面带了Controller
       整句话的意思就是:在com.atguigu包中,只扫描注解是Controller的东西
   -->
    <context:component-scan base-package="com.atguigu" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

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

5、基于注解方式实现属性注入

(1)@Autowired:根据属性类型进行自动装配
第一步 把 service 和 dao 对象创建,在 service 和 dao 类添加创建对象注解
第二步 在 service 注入 dao 对象,在 service 类添加 dao 类型属性,在属性上面使用注解

@Service
public class UserService {
//定义 dao 类型属性
//不需要添加 set 方法
//添加注入属性注解
@Autowired 
private UserDao userDao;
public void add() {
System.out.println("service add.......");
	userDao.add();
} }

(2)@Qualifier:根据名称进行注入
这个@Qualifier 注解的使用,和上面@Autowired 一起使用

//定义 dao 类型属性
//不需要添加 set 方法
//添加注入属性注解
@Autowired //根据类型进行注入
@Qualifier(value = "userDaoImpl1") //根据名称进行注入
private UserDao userDao; 

(3)@Resource:可以根据类型注入,可以根据名称注入

//@Resource //根据类型进行注入
@Resource(name = "userDaoImpl1") //根据名称进行注入
private UserDao userDao; 

(4)@Value:注入普通类型属性

@Value(value = "abc")
private String name; 

6、完全注解开发 (了解即可)

(1)创建配置类,替代 xml 配置文件

@Configuration //作为配置类,替代 xml 配置文件
@ComponentScan(basePackages = {"com.atguigu"})
public class SpringConfig {
}

(2)编写测试类

@Test
public void testService2() {
 //加载配置类
	ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
	UserService userService = context.getBean("userService", 
	UserService.class);
	System.out.println(userService);
	userService.add();
}
posted @ 2021-04-18 22:36  暗影月色程序猿  阅读(33)  评论(0编辑  收藏  举报