首页 > 代码库 > Spring实例化bean的三种方法
Spring实例化bean的三种方法
1.用构造器来实例化
[html] view plain copy print?
- <bean id="hello2" class="com.hsit.hello.impl.ENhello" />
2.使用静态工厂方法实例化
要写一个bean,bean中定义一个静态方法,生成bean,配置factory-method指定静态方法,运行时容器就会自动调用静态方法生成实例
bean
[java] view plain copy print?
- package com.hsit.hello.impl;
- import com.hsit.hello.IHello;
- public class CHhello implements IHello {
- private String msg;
- public void sayHello() {
- System.out.println("中文" + msg);
- }
- public String getMsg() {
- return msg;
- }
- public void setMsg(String msg) {
- this.msg = msg;
- }
- @Override
- public String toString() {
- // TODO Auto-generated method stub
- return "Chinese";
- }
- public static CHhello createInstance() {
- System.out.println("jingtai");
- return new CHhello();
- }
- }
配置文件
[html] view plain copy print?
- <bean id="hello1" class="com.hsit.hello.impl.CHhello" factory-method="createInstance" lazy-init="true">
- <!-- setter注入 -->
- <property name="msg" value=http://www.mamicode.com/"哈哈">
- </property>
- </bean>
3.使用实例工厂方法实例化
要写两个bean,一个是要实例化的bean,另一个是工厂bean。容器先实例化工厂bean,然后调用工厂bean配置项factory-method中指定的静态方法,在方法中实例化bean
[java] view plain copy print?
- package com.hsit.hello.impl;
- public class ENhelloFactory {
- public ENhello createInstance() {
- System.out.println("ENhello工厂");
- return new ENhello();
- }
- public ENhelloFactory() {
- System.out.println("chuanjian");
- }
- }
[java] view plain copy print?
- package com.hsit.hello.impl;
- import com.hsit.hello.IHello;
- public class ENhello implements IHello {
- @Override
- public void sayHello() {
- // TODO Auto-generated method stub
- System.out.println("hello");
- }
- @Override
- public String toString() {
- // TODO Auto-generated method stub
- return "我是ENhello";
- }
- }
配置文件
[html] view plain copy print?
- <bean id="eHelloFactory" class="com.hsit.hello.impl.ENhelloFactory" />
- <!-- factory-bean填上工厂bean的id,指定工厂bean的工厂方法生成实例,class属性不填 -->
- <bean id="example" factory-bean="eHelloFactory" factory-method="createInstance"/>
测试代码
[java] view plain copy print?
- BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
- ENhello eNhello = (ENhello) factory.getBean("example");
- System.out.println(eNhello.toString());
- factory.getBean("hello1");
http://blog.csdn.net/q3498233/article/details/6695580
Spring实例化bean的三种方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。