Spring入门学习——从静态字段中声明Bean

来源:互联网 发布:我的世界透视矿物js 编辑:程序博客网 时间:2024/05/20 03:07
在Java中,常量值往往声明为静态字段。现在打算从一个静态字段中声明Spring IoC容器中的一个Bean。
Spring提供了一个内建的工厂BeanFieldRetrievingFactoryBean(p.s. retrieving是检索,取回的意思~_~)或者使用<util:constant>标记。

应用场景:仍然是熟悉的商品折扣代码:代码还是这个

我们在Product类中定义两个产品常量

package com.cgy.springrecipes.shop;

public abstract class Product {

private String name;
private double price;
public static final Product KINGSTON = new Battery("kingston",2.5);
public static final Product TAYLOR = new Disc("taylor",1.5);

......

}

准备工作已经做好了,现在需要的是在xml配置文件中声明一个Bean来达到从静态字段声明Bean的要求。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"

xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"

xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<bean id="battery"
class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
<property name="staticField">
<value>com.cgy.springrecipes.shop.Product.KINGSTON</value>
</property>
</bean>

<bean id="disc"
class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
<property name="staticField">
<value>com.cgy.springrecipes.shop.Product.TAYLOR</value>
</property>
</bean>

</beans>

如果配置文件中的常量名写错了,将会抛出java.lang.NoSuchFieldException异常。同时value是全限定类名.常量名
***************************************************************************************************************************************
Spring2和更新的版本允许使用<util:constant>标记从静态字段声明一个Bean,对比使用FieldRetrevingFactoryBean,更为简单。但是要注意配置util schema
代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<util:constant id="battery" static-field="com.cgy.springrecipes.shop.Product.KINGSTON"/>

<util:constant id="disc" static-field="com.cgy.springrecipes.shop.Product.TAYLOR"/>
</beans>



0 0
原创粉丝点击