欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【spring学习】bean的三种实例化方法

程序员文章站 2022-05-22 20:26:06
...
  1. 先创建三个类
public class BeanClass {
  public String message;
  public BeanClass(){
      message="构造方法实例化";
  }
  public BeanClass(String s)
  {
      message = s;
  }
}


public class BeanInstanceFactory {
    public BeanClass createBeanClassFactory(){
        return new BeanClass("实例工厂实例化");
    }
}

public class BeanStaticFactory {
    public static BeanClass beanClass = new BeanClass("静态工厂实例化bean");
    public static BeanClass createInstance(){
        return beanClass;
    }
}

2.编写config类


public class BeanConfig {
    //使用@Bean定义三个bean
    @Bean(value= "beanclass")
    public BeanClass getBeanClass(){
        return new BeanClass();
    }
    @Bean(value = "beanStaticFactory")
    public BeanClass getBeanStaticFactory(){
        return BeanStaticFactory.createInstance();
    }
    @Bean(value = "beanInstanceFactory")
    public BeanClass getBeanInstanceFactory(){
        BeanInstanceFactory beanInstanceFactory = new BeanInstanceFactory();
        return beanInstanceFactory.createBeanClassFactory();
    }
}

3.测试:

public class TestBean {
    public static void main(String[] args) {
        //初始化spring容器ApplicationContext
        AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(BeanConfig.class);
      //对应config中的  @Bean(value= "beanclass")
        BeanClass bi = (BeanClass) app.getBean("beanclass");
        System.out.println(bi+bi.message);
        BeanClass b2 = (BeanClass) app.getBean("beanStaticFactory");
        System.out.println(b2+b2.message);
        BeanClass b3 = (BeanClass) app.getBean("beanInstanceFactory");
        System.out.println(b3+b3.message);
    }
}

输出:
【spring学习】bean的三种实例化方法