1

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

 <!-- 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>
4

2 回答 2

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"/>
于 2012-06-01T11:44:33.300 回答
1

如果您使用的是 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"/>
于 2012-06-01T11:40:30.837 回答