当前位置: 代码迷 >> J2EE >> Spring 构造方式注入枚举类型 如何写
  详细解决方案

Spring 构造方式注入枚举类型 如何写

热度:524   发布时间:2016-04-22 00:56:21.0
Spring 构造方式注入枚举类型 怎么写
RT 使用构造方式注入枚举类型,比如org.apache.lucene.index.IndexWriter.MaxFieldLength.LIMITED是枚举类型,那么在<constructor-arg 中怎么写?

<bean id="a" class="A">
  <constructor-arg type="" value="" />
  </bean>

------解决方案--------------------
package lee;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanTest
{
public static void main(String[] args)throws Exception
{
//创建Spring容器
ApplicationContext ctx = new
ClassPathXmlApplicationContext("bean.xml");
//获取chinese 实例
Person p = (Person)ctx.getBean("chinese");
//调用useAxe()方法
p.useAxe();
}
}

<?xml version="1.0" encoding="GBK"?>
<!-- 指定Spring配置文件的DTD信息 -->
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<!-- Spring配置文件的根元素 -->
<beans>
<!-- 配置chinese实例,其实现类是lee.Chinese -->
<bean id="chinese" class="lee.Chinese">
<!-- 使用构造注入,为chinese实例注入steelAxe实例 -->
<constructor-arg ref="steelAxe"/>
</bean>
<!-- 配置steelAxe实例,其实现类是lee.SteelAxe -->
<bean id="steelAxe" class="lee.SteelAxe"/>
<!-- 配置stoneAxee实例,其实现类是lee.StoneAxe -->
<bean id="stoneAxe" class="lee.StoneAxe"/>
</beans>

------解决方案--------------------
不点内容:
package lee;


public class Chinese implements Person
{
private Axe axe;
//默认的构造器
public Chinese()
{
}
//构造注入所需的带参数的构造器
public Chinese(Axe axe)
{
this.axe = axe;
}
//实现Person接口的useAxe方法
public void useAxe()
{
//调用axe的chop()方法,
//表明Person对象依赖于axe对象
System.out.println(axe.chop());
}
}
------解决方案--------------------
XML code
<constructor-arg>    <bean class="org.apache.lucene.index.IndexWriter.MaxFieldLength.LIMITED"/></constuctor-arg><!--或者你为这个枚举类型建立一个bean id,其他依赖该类型的可以将其注入--><bean id="test" class="org.apache.lucene.index.IndexWriter.MaxFieldLength.LIMITED" />注入时候就这样<constructor-arg>    <ref bean="test"/></constructor-arg>
  相关解决方案