【spring学习】bean的三种实例化方法
程序员文章站
2022-05-22 20:26:06
...
- 先创建三个类
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