如何使用弹簧调用方法?

时间:2012-06-01 11:34:21

标签: spring methods

我想在使用spring创建bean之后调用一个方法,例如我创建Factory和schema但我想在创建一个schema bean之前调用Factory的相同方法

 <!-- schemaFactory-->
    <bean id="schemaFact" class="javax.xml.validation.SchemaFactory"
        factory-method="newInstance">
        <constructor-arg value="http://www.w3.org/2001/XMLSchema" />
    </bean>

<!-- schema -->
    <bean id="schema" class="javax.xml.validation.Schema"
        factory-bean="schemaFact" factory-method="newSchema">
        <constructor-arg value="3DSecure.xsd" />
    </bean>

2 个答案:

答案 0 :(得分:2)

您可以使用自己的工厂bean而不是javax.xml.validation.SchemaFactory,它将委托给javax.xml.validation.SchemaFactory并调用方法:

public class MySchemaFactory {
    public SchemaFactory newInstance() {
        SchemaFactory factory = SchemaFactory.newInstance();
        factory.callSomeMethod();
        return factory;
    }
}

<bean id="mySchemaFactory" class="com.foo.bar.MySchemaFactory"/>

<bean id="schemaFact"
      factory-bean="mySchemaFactory"
      factory-method="newInstance"/>

答案 1 :(得分:0)

如果您使用的是Spring 3.0 / 3.1,则可以利用Java配置:

@Configuration
class Config {

    @Bean
    public SchemaFactory schemaFact() throws SAXNotSupportedException, SAXNotRecognizedException {
        final SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        schemaFactory.setFeature("apache.org/xml/features/validation/schema-full-checking", false);
        return schemaFactory;
    }


    @Bean
    public Schema schema() throws SAXException {
        return schemaFact().newSchema(new File("3DSecure.xsd"));
    }
}

但是你要调用SchemaFactory上的哪种方法? 似乎所有这些都是getter或setter,所以你可以使用普通的XML注入... 或者创建你自己的FactoryBean

class SchemaFactoryFactoryBean implements FactoryBean<SchemaFactory> {

    @Override
    public SchemaFactory getObject() throws Exception
    {
        final SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        schemaFactory.setFeature("apache.org/xml/features/validation/schema-full-checking", false);
        return schemaFactory;
    }

    @Override
    public Class<?> getObjectType()
    {
        return SchemaFactory.class;
    }

    @Override
    public boolean isSingleton()
    {
        return true;
    }
}

并像这样使用它(不需要factory-method):

<bean id="schemaFact" class="SchemaFactoryFactoryBean"/>