开发者

Spring bean initialization with multiple-arg method

I would like to create the following Spring bean (a JMX monitor) which has a method setThresholds(Number highThreshold,Number lowThreshold).

Could I invoke the method (with two arguments) in the configuration? I don't want to write codes to invoke it.

<bean id="myMo开发者_如何学编程nitor" class="javax.management.monitor.GaugeMonitor" init-method="start">
  <property name="observedObject">
    <bean class="javax.management.ObjectName">
      <constructor-arg value="test.jmx:name=testBean1" />
    </bean>
  </property>
  <property name="observedAttribute" value="testProperty" />
  <property name="granularityPeriod">
    <bean class="java.lang.Float">
      <constructor-arg value="1000" />
    </bean>
  </property>
</bean>


It is possible by using the MethodInvokingFactoryBean (Spring 4.x and 5.x) (It is not my idea, I just found it this forum: http://forum.springsource.org/archive/index.php/t-16354.html)

SomeClass someobject = new SomeClass();
someobject.set("String1","String2");

<bean id="someobject" class="SomeClass" />

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject" ref="someobject">
    <property name="targetMethod" value="set">
    <property name="arguments">
        <list>
            <value>String1</value>
            <value>String2</value>
        </list>
    </property>
</bean>


I've never seen this done. The big idea of Spring is that you create and initialise straight forward beans. Therefore the only methods that will be called are therefore single argument Setters(...) and Constructors. The definition of what's supported will be in the following schema:

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

Your way around this problem is to get your bean to implement InitializingBean and call your method in the void afterPropertiesSet() method:

eg:

public void setHighThreadHold(Number highThreshHold) {}

public void setLowThreashHold(Number lowThreadHold) {}


public void afterPropertiesSet() {
    setThresholds(highThreshold,lowThreshold);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜