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的三个方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
idea ssm项目java程序向串口发送指令并且使用十六进制 rxtx包的方法
网友评论