Spring框架实例化Bean有三种方式:构造方法实例化、静态工厂实例化和实例工厂实例化(其中,最常用的实例方法是构造方法实例化) 演示Bean的实例化过程,具体步骤如下。 1.使用Eclipse创建Web应用并导入JAR包 2.创建实例化Bean的类 3.创建配置类 4.创建测试类 5.运行测试类
package instance; public class BeanClass { public String message; public BeanClass() { message = "构造方法实例化Bean"; } public BeanClass(String s) { message = s; } }
package instance; public class BeanInstanceFactory { public BeanClass createBeanClassInstance() { return new BeanClass("调用实例工厂方法实例化Bean"); } }
package instance; public class BeanStaticFactory { private static BeanClass beanInstance = new BeanClass("调用静态工厂方法实例化Bean"); public static BeanClass createInstance() { return beanInstance; } }
package config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import instance.BeanClass; import instance.BeanInstanceFactory; import instance.BeanStaticFactory; @Configuration public class JavaConfig { /** * 构造方法实例化 */ @Bean(value = "beanClass") // value可以省略 public BeanClass getBeanClass() { return new BeanClass(); } /** * 静态工厂实例化 */ @Bean(value = "beanStaticFactory") public BeanClass getBeanStaticFactory() { return BeanStaticFactory.createInstance(); } /** * 实例工厂实例化 */ @Bean(value = "beanInstanceFactory") public BeanClass getBeanInstanceFactory() { BeanInstanceFactory bi = new BeanInstanceFactory(); return bi.createBeanClassInstance(); } }
package config; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import instance.BeanClass; public class TestBean { public static void main(String[] args) { // 初始化Spring容器ApplicationContext AnnotationConfigApplicationContext appCon = new AnnotationConfigApplicationContext(JavaConfig.class); BeanClass b1 = (BeanClass) appCon.getBean("beanClass"); System.out.println(b1 + b1.message); BeanClass b2 = (BeanClass) appCon.getBean("beanStaticFactory"); System.out.println(b2 + b2.message); BeanClass b3 = (BeanClass) appCon.getBean("beanInstanceFactory"); System.out.println(b3 + b3.message); appCon.close(); } }