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.collecticntype.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 FactoryBean.super.isSingleton();
    }
}

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


    <!--2.提取list集合类型属性注入使用-->
    <bean id="myBean" class="com.atguigu.spring5.factorybean.MyBean">

    </bean>

</beans>
package com.atguigu.spring5.testdemo;

import com.atguigu.spring5.collecticntype.Book;
import com.atguigu.spring5.collecticntype.Course;
import com.atguigu.spring5.collecticntype.Stu;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.testng.annotations.Test;

import javax.naming.Context;

public class TestSpring5Demo1 {
    @Test
    public void test3() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean3.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方法时候创建多实例对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值