美文网首页
spring-FactoryBean的用法

spring-FactoryBean的用法

作者: guessguess | 来源:发表于2020-06-29 11:37 被阅读0次

测试方法还是之前的

@Configuration
@ComponentScan(basePackages = "com.gee")
public class Config {
    
    public static void main(String args[]) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
        System.out.println(applicationContext.getBean(Student.class));
    }
}

我们来看看FactoryBean接口的定义

public interface FactoryBean<T> {


    @Nullable
    T getObject() throws Exception;

    @Nullable
    Class<?> getObjectType();

    default boolean isSingleton() {
        return true;
    }
}

下面我们定义一个类
public class Student {

}

随后实现FactoryBean接口
@Component    需要被spring管理,所以需要注册到spring的容器中去。
public class StudentFactoryBean implements FactoryBean<Student>{

    @Override
    public Student getObject() throws Exception {
        // TODO Auto-generated method stub
        return new Student();
    }

    @Override
    public Class<?> getObjectType() {
        // TODO Auto-generated method stub
        return Student.class;
    }
}

测试代码,最后的输出结果,说明默认是单例的
com.gee.demo.entity.Student@62e136d3
com.gee.demo.entity.Student@62e136d3
那么下面改写一下方法,将isSingleton改为false,再看看输出结果,结果与上面完全不同
com.gee.demo.entity.Student@62e136d3
com.gee.demo.entity.Student@c8e4bb0

相关文章

网友评论

      本文标题:spring-FactoryBean的用法

      本文链接:https://www.haomeiwen.com/subject/bayhxktx.html