Spring中的Bean实现的创建三种方式

时间:2022-07-16 21:15:51

Spring中的Bean实现的创建方式

1.调用构造器"new"一个Bean实现

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 采用Set注入的方式依赖 -->
<bean id="chinese" class="com.jask.spring.Chinese">
<property name="meiGou">
<ref local="meiGou" />
</property>
</bean>
<bean id="meiGou" class="com.jask.spring.MeiGou"></bean>


</beans>


 

public class Chinese implements Person
{
private Person meiGou;
public Chinese()
{

System.out.println("Chinese init");
}
public void say()
{
meiGou.say();
}

public void sayBye()
{
meiGou.sayBye();
}

public void setMeiGou(MeiGou meiGou)
{
System.out.println("Chinese‘s 依赖关系");
this.meiGou = meiGou;
}
}


 

public class MeiGou implements Person
{
private Chinese chinese;
public MeiGou()
{
System.out.println("MeiGou init");
}
public void say()
{
System.out.println("MeiGou Say");
}

public void sayBye()
{
System.out.println("MeiGou sayBye");
}

public void setChinese(Chinese chinese)
{
this.chinese = chinese;
}
}


 

public class TestMain
{

public static void main(String[] args)
{
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
BeanFactory factory = (BeanFactory)ctx;
Chinese chinese = (Chinese) factory.getBean("chinese");
chinese.say();

}
}

 

结果:

Chinese init
MeiGou init
Chinese‘s 依赖关系
MeiGou Say

 

实例执行顺序:

首先去实现一个Chinese对象的构造器

再去实现依赖的对象MeiGou构造器

然后在去注入依赖关系

最后返回依赖的实现

 

2.采用静态工厂方法创建Bean

只修改了Spring配置文件

<!-- Bean的静态工厂创建实例 -->
<bean id="chinese" class="com.jask.spring.Chinese">
<property name="meiGou">
<ref local="meiGou"/>
</property>
</bean>
<bean id="meiGou" class="com.jask.spring.StaticFactory" factory-method="getPerson">
<constructor-arg>
<value>meiGou</value>
</constructor-arg>
</bean>


 

3.采用实现工厂方法创建Bean

只修改了Spring配置文件

<!-- Bean的实现工厂创建实例 -->
<bean id="staticFactoryBean" class="com.jask.spring.StaticFactory"></bean>
<bean id="chinese" class="com.jask.spring.Chinese">
<property name="meiGou">
<ref local="meiGou"/>
</property>
</bean>
<bean id="meiGou" factory-bean="staticFactoryBean" factory-method="getPerson">
<constructor-arg>
<value>meiGou</value>
</constructor-arg>
</bean>