1

我想初始化一个具有以下属性的bean:

private Iterable<Map.Entry<String, String>> groupToAuthorityMappings;

在我的 context.xml 中,我希望这样做:

<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
         xmlns="http://www.springframework.org/schema/security"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
         http://www.springframework.org/schema/security
         http://www.springframework.org/schema/security/spring-security-3.1.xsd"
         default-autowire="byName">

    <beans:bean id="crowdUserDetailsService"
        class="com.atlassian.crowd.integration.springsecurity.user.CrowdUserDetailsServiceImpl">
        ...
        <beans:property name="groupToAuthorityMappings">
            <beans:map>
                <beans:entry key="Manager" value="ROLE_ADMINISTRATOR,ROLE_USER"/>
            </beans:map>
        </beans:property>
        ...
    </beans:bean>
</beans:beans>

但我收到以下错误:

java.lang.IllegalStateException: Cannot convert value of type [java.util.LinkedHashMap] to required type [java.lang.Iterable] for property 'groupToAuthorityMappings': no matching editors or conversion strategy found

我无法更改 bean,因为它来自提供的库。有人知道我怎样才能实现我的目标吗?

4

2 回答 2

1

如果您将此数据定义为 a Map,则可以使用 afactory-method获取条目的迭代器:

<util:map id='groupToAuthority>
    <beans:entry key="some-group" value="specific-authority-for-group" />
    ...
</util:map>

<bean class='ClassRequiringAnIterable'>
    <constructor-arg>
        <bean factory-bean='groupToAuthority' factory-method='entrySet'/>
    </constructor-arg>
</bean>

但是,请注意您需要一个Iterable<Map.Entry<String, String>>,并且您的示例定义了一个Map<String, List<String>>,因此请确保每个组都映射到一个角色。

于 2014-09-27T14:48:26.903 回答
0

我不会尝试在 spring xml 中创建可迭代对象,而是使用这种方法。为 bean 创建一个工厂:

public class ThirdPartyBeanFactory {

    public ThirdPartyBean getInstance(Map<String,String> map) {
        ThirdPartyBean tpb = new ThirdPartyBean(); //This is the provided object you cant change
        tpb.setGroupToAuthorityMappings(map.entrySet());
        return tpb;
    }
}

然后在 XML 首先创建工厂实例(thirdPartyBeanFactory)和地图(mapBean)。然后像这样定义你的bean:

<bean id="thirdPartyBean" factory-bean="thirdPartyBeanFactory"
        factory-method="getInstance">
    <constructor-arg ref="mapBean" />
</bean>
于 2014-09-26T15:49:41.227 回答