spring核心:bean工厂的装配 2

本文详细介绍了Spring框架中创建Bean的多种方式,包括使用构造函数、静态工厂方法及非静态工厂方法创建Bean的过程,并探讨了Bean标识符的概念及其在Spring中的应用。

本文继续上面的 spring核心:bean工厂的装配系列。主要包含:

3.使用构造函数创建bean

4.使用静态工厂方法创建bean

5.使用非静态工厂方法创建bean

6.bean的标识符

3.使用构造函数创建bean

<bean id="supplier" class="getstart.MessageSupplier"> </bean>

这就相当于spring new出这个对象,这里的bean没有必要是javabean的形式。对于这种形式bean必须存在默认的构造函数,否则报错:

Could not instantiate bean class [beanfactory.SimpleBean]: No default constructor found; nested exception is java.lang.NoSuchMethodException: beanfactory.SimpleBean.<init>()

4.使用静态工厂方法创建bean

这里所指的静态是指“方法是静态的”。这是bean定义中的class就是这个包含静态方法的类。spring调用这个类的静态方法来产生这个类。

/** * */ package beanfactory; /** * @author jefferyxu * */ public class LegacySingleton { private static LegacySingleton instance = null; private LegacySingleton() { } public static LegacySingleton getInstance() { if(null == instance) { instance = new LegacySingleton(); } return instance; } public String toString() { return "i am made by the static class."; } }

<bean id="legacyBean" class="beanfactory.LegacySingleton" factory-method="getInstance" abstract="false" lazy-init="default" autowire="default"> </bean>

在myeclipse可以这么添加:

5.使用非静态工厂方法创建bean

首先添加bean factory bean:

创建bean :

生成代码如下:

<bean id="legacyFactory" class="beanfactory.instancefactory.ConcreteLegacyFactory"> </bean> <bean id="productBean" factory-method="make" factory-bean="legacyFactory" > </bean>

6.bean的标识符

每个bean可以有一个或者是多个id,如果是多个的话,那么spring会认为其他都是第一个id的别名。可以使用getAliases方法得到所有的别名。

上面中出现的问题:

Attribute 'dependency-check' is not allowed to appear in element 'bean'.

这个主要是spring版本的问题:the dependency-check and default-dependency-check elements have been removed in Spring 3.0 hence your validation errors.(http://forum.springsource.org/showthread.php?t=77584)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值