一、实例化bean的方式
1、通过构造方法的方式
2、通过静态方法的方式
3、通过实例化工厂的方式
下面通过代码过一个demo
- 通过构造方法的方式
1)首先创建一个SpringBean 并提供一个构造方法如下所示
public class SpringBean {
String name;
int age;
public SpringBean(){
System.out.println("springbean create,by not params construct function");
}
public SpringBean(String name,int age){
this.name=name;
this.age=age;
System.out.println("springbean create,by construct function");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "SpringBean{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2)applicationContext.xml 的创建方式如下所示
//一种是无参构造方法的方式
<bean id="springBean1" class="springioc6.SpringBean">
<property name="name" value="mumu"></property>
<property name="age" value="18"></property>
</bean>
//另一种是通过有参构造方法的方式
<bean id="springBean2" class="springioc6.SpringBean">
<constructor-arg name="name" value="mumu"></constructor-arg>
<constructor-arg name="age" value="28"></constructor-arg>
</bean>
- 通过静态方法的方式,此处的构建方式类似工厂模式,通过一个工厂的静态方法创建出一个对象。
public class SpringBeanFactory {
/**
* 不带参数的
* @return
*/
public static SpringBean getInstanceSpringBean(){
SpringBean sbean=new SpringBean();
return sbean;
}
/**
* 带参数的
* @return
*/
public static SpringBean getInstanceSpringBeanWithParam(String name,int age){
SpringBean sbean=new SpringBean();
sbean.setName(name);
sbean.setAge(age);
return sbean;
}
}
applicationContext.xml 的配置方法如下
<bean id="springbeanfactory" class="springioc7.SpringBeanFactory" factory-method="getInstanceSpringBean">
<property name="name" value="mouse"></property>
<property name="age" value="23"></property>
</bean>
<bean id="springbeanfactoryParam" class="springioc7.SpringBeanFactory" factory-method="getInstanceSpringBeanWithParam">
<constructor-arg name="name" value="line"></constructor-arg>
<constructor-arg name="age" value="13"></constructor-arg>
</bean>
- 通过实例化工厂的方式
public class SpringBeanFactory {
/**
* 不带参数的
* @return
*/
public SpringBean getInstanceSpringBean(){
SpringBean sbean=new SpringBean();
return sbean;
}
/**
* 带参数的
* @return
*/
public SpringBean getInstanceSpringBeanWithParam(String name, int age){
SpringBean sbean=new SpringBean(name,age);
return sbean;
}
}
applicationContext.xml 的配置如下 首先要有一个工厂bean 然后再通过这个工厂bean 中的方法获得想要创建的对象。 主要涉及的属性是 factory-bean和factory-method
<bean id="factorySpring" class="springioc8.SpringBeanFactory"></bean>
<bean id="springbeanfactory" factory-bean="factorySpring" factory-method="getInstanceSpringBean">
<property name="name" value="glacss"></property>
<property name="age" value="23"></property>
</bean>
<bean id="springbeanfactoryParam" factory-bean="factorySpring" factory-method="getInstanceSpringBeanWithParam">
<constructor-arg name="name" value="flower"></constructor-arg>
<constructor-arg name="age" value="10"></constructor-arg>
</bean>