如何配置一个带泛型的Bean

希望在Spring容器中配置一个带泛型的Bean,直接配置如下:
<bean id="list" class="java.util.ArrayList<java.lang.String>"/>


启动容器时,将报如下所示:
Caused by: org.xml.sax.SAXParseException: The value of attribute "class" associated with an element type "null" must not contain the '<' character.
	at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
	at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:174)
	at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:388)
	at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1427)
	at com.sun.org.apache.xerces.internal.impl.XMLScanner.scanAttributeValue(XMLScanner.java:945)


这是因为“<”或“>”的字符是XML的特殊字符,它会破坏Spring XML配置文件的格式,因此产生了错误


由于Spring 3.0引入了JavaConfig,以代码的方式定义Bean,因此我们可以使用如下方式配置之:
package com.ioctest; /**
 * Copyright:中软海晟信息科技有限公司 版权所有 违者必究 2013 
 */

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class AppConfig {

    @Bean(name = "listStr")
    public List<String> listStrBean(){
        return new ArrayList<String>();
    }
}


在XML配置文件中引用这个JavaConfig:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       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.2.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!--     <bean id="list" class="java.util.ArrayList<java.lang.String>"/>-->

    <context:component-scan base-package="com.ioctest"/>
    <context:annotation-config/>

</beans>


这个就可以正确启动了:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class Tester {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("test.xml");
        List<String> listStr = (List<String>) applicationContext.getBean("listStr");
        listStr.add("ddd");
    }
}

猜你喜欢

转载自stamen.iteye.com/blog/1912650