Spring之三种方法实例化Bean
程序员文章站
2022-05-22 20:26:00
...
1.使用构造方法实例化Bean
Bean1
public class Bean1 {
public Bean1() {
System.out.println("Bean.Bean");
}
}
SpringBeans.xml
<bean id="bean1" class="com.Learn.Class.Bean1" />
Testclass
ApplicationContext ctx=new ClassPathXmlApplicationContext("SpringBeans.xml");
Bean1 bean1=ctx.getBean("bean1",Bean1.class);
System.out.println("bean1 = " + bean1);
2.使用静态方法实例化Bean
Bean2
public class Bean2 {
public Bean2(){
System.out.println("Bean2.Bean2");
}
}
Bean2Factory
public class Bean2Factory {
public static Bean2 getBean2(){
return new Bean2();
}
}
SpringBeans.xml
<bean id="bean2" class="com.Learn.Class.Bean2Factory" factory-method="getBean2"/>
TestClass
ApplicationContext ctx=new ClassPathXmlApplicationContext("SpringBeans.xml");
Bean2 bean2 = ctx.getBean("bean2",Bean2.class);
System.out.println("bean2 = " + bean2);
3.使用实例方法实例化Bean
Bean3
public class Bean3 {
public Bean3(){
System.out.println("Bean3.Bean3");
}
}
Bean3Factory
public class Bean3Factory {
public Bean3 getBean3(){
return new Bean3();
}
}
SprinBeans.xml
<bean id="bean3Factory" class="com.Learn.Class.Bean3Factory" />
<bean id="bean3" factory-bean="bean3Factory" class="com.Learn.Class.Bean3" factory-method="getBean3"/>
TestClass
ApplicationContext ctx=new ClassPathXmlApplicationContext("SpringBeans.xml");
Bean3 bean3 = ctx.getBean("bean3",Bean3.class);
System.out.println("bean3 = " + bean3);