Spring 使用FactoryBean创建Bean

一、准备工作

1、导入spring-context依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.22.RELEASE</version>
</dependency>

2、创建实体类Color

public class Color {

}

二、使用FactoryBean

1、创建ColorFactoryBean

import org.springframework.beans.factory.FactoryBean;

public class ColorFactoryBean implements FactoryBean<Color> {

    @Override
    public Color getObject() throws Exception {
        return new Color();
    }

    @Override
    public Class<?> getObjectType() {
        return Color.class;
    }

    @Override
    public boolean isSingleton() {
        // 返回true为单例模式,否则每次都是调用getObject()方法
        return true;
    }

}

2、创建BeanConfig配置类

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

@Configuration
public class BeansConfig {

    @Bean
    public ColorFactoryBean colorFactoryBean(){
        return new ColorFactoryBean();
    }

}

3、开始测试

public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeansConfig.class);
    Object colorFactoryBean = context.getBean("colorFactoryBean");
    System.out.println(colorFactoryBean);
    // 控制台打印的是Color对象,而不是ColorFactoryBean
    Object colorFactoryBean2 = context.getBean("&colorFactoryBean");
    System.out.println(colorFactoryBean2);
    // 通过& + name的方式获取bean,可以获取到ColorFactoryBean
}

三、总结分析

本章主要学习了,使用FactoryBean创建Bean。《参考资料》

猜你喜欢

转载自blog.csdn.net/weixin_40968009/article/details/129786031
今日推荐