Bean的三种被实例化的方法

在Spring中有三个实例化bean的方式:

1.使用构造器实例化

2.使用静态工厂方法实例化

3.使用实例化工厂方法实例化

(使用最普遍的是第一种,使用构造器实例化)

(1)使用构造器实例化

这种方法我们使用的最多,因为不再用去创建工厂类.最简单

测试类:

public class InstanceTest1 {
       public static void main(String[] args) {
     	String xmlPath = "com/itheima/instance/constructor/beans1.xml";
               ApplicationContext applicationContext = 
			    new ClassPathXmlApplicationContext(xmlPath);
	Bean1 bean = (Bean1) applicationContext.getBean("bean1");
                System.out.println(bean);
      }
}

在xml中配置也是很简单

  <bean id="bean1" class="com.itheima.instance.constructor.Bean1" />

(2)使用静态工厂方法实例化

想要使用此种实例化方法必需要有工厂类,而且工厂里要有静态方法

测试类:

public class InstanceTest2 {
         public static void main(String[] args) {
	String xmlPath ="com/itheima/instance/static_factory/beans2.xml";
 	ApplicationContext applicationContext = 
 			         new ClassPathXmlApplicationContext(xmlPath);
 	System.out.println(applicationContext.getBean("bean2"));
         }
  }

静态工厂:

public class MyBean2Factory {
    public static Bean2 createBean(){
        return new Bean2();
    }
}

xml:

    <bean id="bean2" class="com.itheima.instance.constructor.MyBean2Factory" factory-method="createBean"/>

此种方法的xml和第一种有区别,需注意.

id是实例化对象的名称,class里面写工厂类,而factory-method是实现实例化类的静态方法

(3)使用实例化工厂方法实例化:

测试类:

public class InstanceTest3 {
    public static void main(String[] args) {
        String xmlPath = "applicationContext.xml";
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(xmlPath);
        System.out.println(applicationContext.getBean("bean3"));
    }
}

工厂类:

public class MyBean3Factory {
    public Bean3 createBean(){
        return new Bean3();
    }
}

xml:

<bean id="myBean3Factory" class="com.itheima.instance.constructor.MyBean3Factory"/>
<bean id="bean3" factory-bean="myBean3Factory" factory-method="createBean"  />

此种方法需要注意,由于使用的是实例化工厂方法实例化,想要创建bean对象必须,得调用工厂方法,然后想要调用方法还必须要有工厂的对象,所以需要给工厂也写个bean标签.其中factory-bean对应被实例化工厂类的对象的名称,factory-method是工厂的非静态方法.



 


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值