spring5基础学习之ioc——1

关于spring5中iocbean管理中有两种类型 bean,一种普通 bean,另外一种工厂 bean(FactoryBean)。

按我的理解是普通bean,配置中定义什么类型就是什么类型。

工厂 bean返回的类型可以不一样。

使用工厂bean要继承FactoryBean<>,话不多说上代码

<?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="factorybean.Mybean">

    </bean>
</beans>
View Code
package factorybean;

import 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("asd");
        return course;
    }

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

    @Override
    public boolean isSingleton() {
        return FactoryBean.super.isSingleton();
    }
}
View Code

 

接着在来说说如何设置实例还是多实例,它通过设置 scope 值来完成

设置 scope 值是 singleton 时候,创建单实例对象

设置 scope 值是 prototype 时候,创建多实例对象
<bean id="book" class="collectiontype.Book" scope="prototype">
<property name="booklist" ref="list"></property>
</bean>
posted @ 2022-04-11 17:04  chenghaixinag  阅读(27)  评论(0)    收藏  举报