Spring实例化bean的三种方法
Posted 旧爱久居于心
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring实例化bean的三种方法相关的知识,希望对你有一定的参考价值。
1.用构造器来实例化
- <bean id="hello2" class="com.hsit.hello.impl.ENhello" />
2.使用静态工厂方法实例化
要写一个bean,bean中定义一个静态方法,生成bean,配置factory-method指定静态方法,运行时容器就会自动调用静态方法生成实例
bean
- 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();
- }
- }
配置文件
- <bean id="hello1" class="com.hsit.hello.impl.CHhello" factory-method="createInstance" lazy-init="true">
- <!-- setter注入 -->
- <property name="msg" value="哈哈">
- </property>
- </bean>
3.使用实例工厂方法实例化
要写两个bean,一个是要实例化的bean,另一个是工厂bean。容器先实例化工厂bean,然后调用工厂bean配置项factory-method中指定的方法,在方法中实例化bean
工厂bean:
- package com.hsit.hello.impl;
- public class ENhelloFactory {
- public ENhello createInstance() {
- System.out.println("ENhello工厂");
- return new ENhello();
- }
- public ENhelloFactory() {
- System.out.println("chuanjian");
- }
- }
要实例化的bean:
- 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";
- }
- }
配置文件
- <bean id="eHelloFactory" class="com.hsit.hello.impl.ENhelloFactory" />
- <!-- factory-bean填上工厂bean的id,指定工厂bean的工厂方法生成实例,class属性不填 -->
- <bean id="example" factory-bean="eHelloFactory" factory-method="createInstance"/>
测试代码
- BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
- ENhello eNhello = (ENhello) factory.getBean("example");
- System.out.println(eNhello.toString());
- factory.getBean("hello1");
以上是关于Spring实例化bean的三种方法的主要内容,如果未能解决你的问题,请参考以下文章