温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-14 20:36:04 来源:脚本之家 阅读:101 作者:Niel 栏目:编程语言

1.构造器

也就是在上一篇讲的那个例子,调用默认的无参构造函数

2.静态工厂方法

1)创建需要执行的方法的类

public class HelloWorld {
   
  public HelloWorld(){
    System.out.println("aaaa");
  }
   
  public void hello(){
    System.out.println("hello world");
  }
}

2)创建静态工厂

public class HelloWorldFactory {
  public static HelloWorld getInstance(){
    return new HelloWorld();
  }
}

3)编写applicationContext.xml配置文件

<?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>

4)启动容器,创建对象,调用方法

@Test
  public void test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    HelloWorld world = (HelloWorld)context.getBean("helloWorld2");
    world.hello();
  }

3.实例工厂方法(略)

以上这篇浅谈springioc实例化bean的三个方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI