简体   繁体   中英

Invoke Java Constructor with Arbitrary number of argument in Spring XML

Assume that there is a class having constructor with arbitrary number of arguments like this:

public ClassA(URI ... uri){
    //contruct object
}

The number of URI objects to pass into ClassA's constructor may varies depending on number of values defined in config file (can be one to many URIs).

How should I define a ClassA bean in Spring XML?

Use the FactoryBean interface:

public interface FactoryBean<T> {
  T getObject() throws Exception;
  Class<T> getObjectType();
  boolean isSingleton();
}

Basically define of bean of that type. Something like this:

<bean id="classA" class="ClassAFactoryBean"/>

And then:

public class ClassAFactoryBean implements FactoryBean<ClassA> {

   @Value("${uris}")
   URI[] uris;

   ClassA getObject() throws Exception {
       return new ClassA(uris);
   }

   Class<T> getObjectType() {
       return ClassA.class;
   }

   boolean isSingleton() {
       return true;
   }
}

You may have to inject the "uris" properties as String and then converting if there's no converter provided by Spring. Or hook your own URI converter.

The following configuration works fine:

<beans>
  <bean id="ClassA" class="ClassA">
      <constructor-arg ref="uri"/>
   </bean>

   <bean id="uri" class="URI"/>
</beans>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM