下面小编就为大家带来一篇浅谈springioc实例化bean的三个方法。小编觉得挺不错的,现在就想给大家,也给大家做个参考。一起跟随小编过来看看吧
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方法介绍的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号