Spring:bean作为Java Config中的构造函数参数

时间:2014-04-22 09:03:39

标签: java spring

翻译这个bean的正确方法是:

<bean id="artifactBinding" class="org.springframework.security.saml.processor.HTTPArtifactBinding">
    <constructor-arg ref="parserPool"/>
    <constructor-arg ref="velocityEngine"/>
    <constructor-arg>
        <bean class="org.springframework.security.saml.websso.ArtifactResolutionProfileImpl">
            <constructor-arg>
                <bean class="org.apache.commons.httpclient.HttpClient">
                    <constructor-arg>
                        <bean class="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager"/>
                    </constructor-arg>
                </bean>
            </constructor-arg>
            <property name="processor">
                <bean class="org.springframework.security.saml.processor.SAMLProcessorImpl">
                    <constructor-arg ref="soapBinding"/>
                </bean>
            </property>
        </bean>
    </constructor-arg>
</bean>

<bean id="soapBinding" class="org.springframework.security.saml.processor.HTTPSOAP11Binding">
    <constructor-arg ref="parserPool"/>
</bean>

从XML到Java-Config?

2 个答案:

答案 0 :(得分:3)

您还可以通过形成

来缩小所需协作者对象的范围
@Bean
public HTTPArtifactBinding artifactBinding(ParserPool parserPool, VelocityEngine velocityEngine) {
    return new HTTPArtifactBinding(parserPool, velocityEngine, artifactResolutionProfile());
}

如果Spring可以解析parserPool和velocityEngine,那么它可以注入你的@Bean def方法。

答案 1 :(得分:0)

@Configuration
public class Configuration {

    @Autowired
    private ParserPool parserPool;

    @Autowired
    private VelocityEngine velocityEngine;

    @Bean
    public HTTPArtifactBinding artifactBinding() {
        return new HTTPArtifactBinding(parserPool, velocityEngine, artifactResolutionProfile());
    }

    private ArtifactResolutionProfile artifactResolutionProfile() {
        final ArtifactResolutionProfile artifactResolutionProfile = new ArtifactResolutionProfile(new HttpClient(new MultiThreadedHttpConnectionManager()));
        artifactResolutionProfile.setProcessor(new SAMLProcessorImpl(soapBinding()));
        return artifactResolutionProfile;
    }

    @Bean
    public HTTPSOAP11Binding soapBinding() {
        return new HTTPSOAP11Binding(parserPool);
    }
}