bean的实例化方式

spring中bean的实例化方式有三种,1.构造器实例化,2.实例工厂实例化,3.静态工厂实例化

1.构造器实例化方式

public class bean1 {
public bean1() {
}
}
applicatContext.xml中的配置
<bean id="bean1" class="com.itheima.ioc.Constructorbean.bean1"/>
测试
public class consTest {
public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
bean1 bean=(bean1) applicationContext.getBean("bean1");
}
}

2.静态工厂实例化bean
public class Bean2 {
public Bean2() {
}
}
//静态工厂类
public class MyFactoryBean2 {
public static Bean2 creatBean() {
return new Bean2();
}
}

applicatContext.xml中的配置
<bean id="bean2" class="com.itheima.ioc.StaticFactoryshilihuaBean2.MyFactoryBean2"
factory-method="creatBean"/>
测试:
public class TestFactoryBean {
public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
Bean2 bean2=(Bean2)applicationContext.getBean("bean2");
System.out.println(bean2);
}
}
3.实例工厂实例化bean
public class bean3 {
}
实例工厂类
public class MyBeanFactory {
public MyBeanFactory() {
System.out.println("这是实例化工厂实例化bean...");
}

public bean3 createBeanFactory() {
return new bean3();
}
}
applicationContext.xml中的配置
 <bean id="MybeanFactory" class="com.itheima.ioc.shiligongcshilihBean3.MyBeanFactory"/>
<bean id="bean3" factory-bean="MybeanFactory" factory-method="createBeanFactory"/>
测试
public class shilihuabeanTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
bean3 bean=(bean3)applicationContext.getBean("bean3");
System.out.println(bean);
}
}
posted @ 2019-03-20 16:12  jason小蜗牛  阅读(357)  评论(0编辑  收藏  举报