Spring bean initialization with multiple-arg method - java

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="myMonitor" 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);
}

Related

How to declare the spring bean during its initialization

I need to do something like this.
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.example.Converter1"/>
<bean class="com.example.Converter2"/>
<bean id="converter3" class="com.example.Converter3"/>
<bean id="converter4" class="com.example.Converter4">
<property name="conversionService" ref="converter3"/>
</bean>
<bean id="converter5" class="com.example.Converter5">
<property name="conversionService" ref="converter4"/>
</bean>
</set>
</property>
</bean>
I want to use converter3 bean into converter4 bean via #Autowired annotation. Can I do this or it is bad way for programming?
Please, help me to solve this problem?
It's not 100% clear what you want, but in case you mean to inject instance of converter3 into converter4 class using #Autowired it's OK.

Override xml-defined spring bean in java-based configuration

I'm extending a complete product called Hippo CMS with my own REST interface. Hippo CMS is using Apache CXF for rest and acquires resources definitions from a spring bean defined somewhere in Hippo CMS sources. This definition look like this:
<bean id="jaxrsRestPlainResourceProviders" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="org.apache.commons.collections.ListUtils" />
<property name="targetMethod" value="union" />
<property name="arguments">
<list>
<ref bean="customRestPlainResourceProviders" />
<ref bean="defaultRestPlainResourceProviders" />
</list>
</property>
</bean>
<bean id="defaultRestPlainResourceProviders" class="org.springframework.beans.factory.config.ListFactoryBean">
<property name="sourceList">
<list>
</list>
</property>
</bean>
<!-- Default empty list of custom plain resource providers to be overriden. -->
<bean id="customRestPlainResourceProviders" class="org.springframework.beans.factory.config.ListFactoryBean">
<property name="sourceList">
<list>
</list>
</property>
</bean>
I need to override customRestPlainResourceProviders bean with my own bean. It works fine from XML configuration looking like this:
<bean id="customRestPlainResourceProviders" class="org.springframework.beans.factory.config.ListFactoryBean">
<property name="sourceList">
<list>
<bean class="org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider">
<constructor-arg>
<bean class="com.xxx.rest.FolderStructureResource"/>
</constructor-arg>
</bean>
</list>
</property>
</bean>
But it doesn't work if I define a bean in Java configuration class (which in the case of other beans works completely fine):
#Bean(name = "customRestPlainResourceProviders")
public ListFactoryBean customRestPlainResourceProviders() {
ListFactoryBean listFactoryBean = new ListFactoryBean();
listFactoryBean.setSourceList(
Lists.newArrayList(
new SingletonResourceProvider(
new FolderStructureResource(repository())
)
)
);
return listFactoryBean;
}
Is there a way to override a bean defined in XML configuration with a bean created in Java configuration class?
What version of spring are you using? I believe this issues is addressed in 4.2.

How to use javax.inject Provider<T> within spring xml configuration

I have a class called let's say A with such a setter:
//class A
#Inject
public void setAProvider(Provider<B> b)
{
this.b = b;
}
It works fine with javax.inject and annotation configuration when I want to have only one kind of A instance..
My problem is that I want to have two instances of class A, one with Provider<B1> and second with Provider<B2>. My question is how to express my requirements in Spring xml configuration?
Actually, it is briefly answered here, you need ProviderCreatingFactoryBean .
This is an example :
<bean id="a" class="a.b.b.A" scope="prototype">
<property name="xxx" value="15000"/>
</bean>
<bean id="b" class="a.b.b.B" scope="prototype">
<property name="zzz" value="-1"/>
</bean>
<bean id="providerOfA" class="org.springframework.beans.factory.config.ProviderCreatingFactoryBean">
<property name="targetBeanName" value="a"/>
</bean>
<bean id="providerOfB" class="org.springframework.beans.factory.config.ProviderCreatingFactoryBean">
<property name="targetBeanName" value="b"/>
</bean>
<bean id="barServiceA" class="a.b.c.BarService">
<property name="provider" ref="providerOfA"/>
</bean>
<bean id="barServiceB" class="a.b.c.BarService">
<property name="provider" ref="providerOfB"/>
</bean>

Is there a way to get all registered message-converters?

I would like to somehow inject all HttpMessageConverter instances registered in Spring-MVC. I can successfully inject all that have been registered via.
private HttpMessageConverter[] converters;
#Autowired
public void setConverters(HttpMessageConverter[] converters) {
this.converters = converters;
}
However this only injects if the converter was registered inside the context (i.e. if defined outside of <annotation-driven>).
I did figure I would try using <beans:ref inside the <annotation-driven><message-converters> but it is not supported in spring-web 3.1.
Is there some class I can inject that may have a property I could use to get converters? Ideally I'd like to see the order in the filter chain they are registered in too.
You are right, the message converters are directly instantiated within the RequestMappingHandlerAdapter registered using the <mvc:annotation-driven/> xml tag, and the message-converters subtag explicitly expect the bean to be defined inline.
However, a workaround is to define the handler adapter and inject in the converters this way:
<bean name="handlerAdapter" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer">
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="conversionService" ref="conversionService"></property>
<property name="validator">
<bean class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
</bean>
</property>
</bean>
</property>
<property name="messageConverters">
<list>
<ref bean="byteArrayConverter"/>
<ref bean="jaxbConverter"/>
<ref bean="jsonConverter"/>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"></bean>
<bean class="org.springframework.http.converter.ResourceHttpMessageConverter"></bean>
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"></bean>
<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"></bean>
</list>
</property>
</bean>
<bean name="byteArrayConverter" class="org.springframework.http.converter.ByteArrayHttpMessageConverter"></bean>
<bean name="jaxbConverter" class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"></bean>
<bean name="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean name="handlerMapping" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
<property name="useSuffixPatternMatch" value="false"></property>
</bean>
Spring puts all the converters behind an implementation of org.springframework.core.convert.ConversionService . You need to inject an instance of that interface into your class, you can read more in the spring documentation (including an example of how to inject it).
You can try injecting a bean of type RequestMappingHandlerAdapter but depending on your configuration, you might not have an instance!

Common value configuration in Spring XML

I have several Spring beans in which one of the property value for all of them are same String value. Is there a way where I can define this String in XML at one place and refer it in all beans at property value settings?
<bean id="somebean" class="test.SomeBean">
<property name="property1" ref="someValue"></property>
<property name="commonProperty" value="commonValue"></property>
<bean id="nextBean" class="test.NextBean">
<property name="property2" ref="someValue"></property>
<property name="commonProperty" value="commonValue"></property>
How to set commonValue in a seperate place and refer it in both places?
Try like this.
<bean id="commonConfig" abstract="true">
<property name="commonField" value="CommonValue"></property>
</bean>
<bean id="class1" class="com.dataclass.Class1" parent="commonConfig">
<property name="field1" value="value1"></property>
</bean>
<bean id="class2" class="com.dataclass.Class2" parent="commonConfig">
<property name="field2" value="value2"></property>
</bean>
Class1 & Class2 having one common field name "commonField", parent attribute is use for this common purpose only.
In Spring this is called bean definition inheritance(this is not java class inheritance, above example Class1 & n Class not inheriting in their respective java file.)
For more detail, look at Spring doc's link.
I've never tried it before, but this should work
<bean id="commonProp" class="java.lang.String">
<constructor-arg name="original" value="yourString"></constructor-arg>
</bean>
Then, in every bean you need to reference it:
<bean id="somebean" class="test.SomeBean">
<property name="property1" ref="someValue"></property>
<property name="commonProperty" ref="commonProp"></property>
</bean>
You can define your string properties in some "init_constants.properties" file. Then you should load properties file in spring xml:
<bean id="properties"
class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:db.properties</value>
<value>classpath:mail.properties</value>
<value>classpath:init_constants.properties</value>
</list>
</property>
</bean>
And after that you can inject this properties using xml:
<bean id="somebean" class="test.SomeBean">
<property name="property1" ref="{$prop1}"></property>
<property name="commonProperty" value="commonValue"></property>
</bean>
or in code using #Value annotation:
#Value(value="${prop1}")
private String property1;
Well If commonValue is string then you can put it in properties file and read it using #Value annotation.

Categories

Resources