源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

浅谈springioc实例化bean的三个方法

  • 时间:2020-10-21 03:14 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:浅谈springioc实例化bean的三个方法
[b]1.构造器[/b] 也就是在上一篇讲的那个例子,调用默认的无参构造函数 [b]2.静态工厂方法[/b] [b]1)创建需要执行的方法的类[/b]
public class HelloWorld {
   
  public HelloWorld(){
    System.out.println("aaaa");
  }
   
  public void hello(){
    System.out.println("hello world");
  }
}
[b]2)创建静态工厂[/b]
public class HelloWorldFactory {
  public static HelloWorld getInstance(){
    return new HelloWorld();
  }
}

[b]3)编写applicationContext.xml配置文件[/b]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  <!--
    在这个配置中,spring容器要用默认的构造函数为HelloWorld创建对象
   -->
  <bean id="helloWorld" class="HelloWorld"></bean>
   
  <!--
    采用静态工厂方法创建对象
      factory-method为工厂方法
   -->
   <bean id="helloWorld2" class="HelloWorldFactory" factory-method="getInstance"></bean>
</beans>

[b]4)启动容器,创建对象,调用方法[/b]
@Test
  public void test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    HelloWorld world = (HelloWorld)context.getBean("helloWorld2");
    world.hello();
  }
[b]3.实例工厂方法(略)[/b] 以上这篇浅谈springioc实例化bean的三个方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部