<bean id="cObject" scope="request" class="x.y.z.CClass"/>
<bean id="bObject" scope="request" class="x.y.z.BClass"/>
<bean id="aObject" scope="request" class="x.y.z.AClass">
<constructor-arg ref="bObject" />
<property name="cRef" ref="cObject" />
</bean>
aObject.cRef is not getting set for some reason. Note that constructor-arg and property are used in the same definition. I have not seen an example / post with similar feature.
On same sources my colleague discover:
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'service.MenuService#0'
defined in class path resource [spring-beans/integrator.xml]:
Could not resolve matching constructor (hint: specify index/type/name
arguments for simple parameters to avoid type ambiguities)
while my host, test and production servers have no such error.
With:
<bean class="service.MenuService">
<constructor-arg index="0" type="java.lang.String" value="#{user}"/>
<constructor-arg index="1" type="java.lang.String" value="#{password}"/>
<constructor-arg index="2" type="java.lang.String" value="#{uri}"/>
<property name="system" value="OPRT"/>
<property name="client" value="OPRT"/>
</bean>
while there are only one 3-args constructor in bean.
The reason to use constructor - it perform some additional actions on non-Spring library by invoking init() method. And set args as fields.
So I change spring-beans.xml to:
<bean class="service.MenuService" init-method="init">
<property name="login" value="#{user}"/>
<property name="password" value="#{password}"/>
<property name="httpsUrl" value="#{uri}"/>
<property name="system" value="OPRT" />
<property name="client" value="OPRT" />
</bean>
Take attention to init-method= part.
UPDATE After all I wrote simple XML config and step through Spring source code in debugger. Seems that with Spring 3.x it's possible to combine constructor-arg and property in XML bean definition (check doCreateBean in AbstractAutowireCapableBeanFactory.java, which call createBeanInstance and populateBean next).
See also https://softwareengineering.stackexchange.com/questions/149378/both-constructor-and-setter-injection-together-in-spring/
Mixing <constructor-arg> and <property> is generally a bad idea.
There is only one good reason for using <constructor-arg>, and that is to create immutable objects.
However, your objects are not immutable if you can set their properties. Don't use <constructor-arg>. Redesign the class, use an initializer method annotated with #PostConstruct if you need to apply some logic at bean creation time.
Related
I have the project structure as following -
Facade -> Service-> DAO
In the DAO layer, when the beans are initialized then many dependencies are injected from a property file. Therefore, the properties file must be read first and then the remaining dao beans must be created. When the application is started then it gives an error that Spring cannot resolve a placeholder.
The DAO-application-context.xml is like-
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="prop">
<value>app.properties</value>
</property>
</bean>
<import resource = "a-dao.xml" />
<import resource = "b-dao.xml" />
<import resource = "c-dao.xml" />
Now in all the child application contexts i.e. a-dao, etc, we have-
<bean ....>
<property name = "xyz">
<value>${appValue}<value/>
</property>
<bean>
The error received is that appValue cannot be resolved. I think that it may be due to incorrect sequence of bean creation. However, the same config is working in another larger project.
I have checked Order of Spring Bean Initialization but implementing that solution would not be feasible. Is there any other way ?
Reg this Block of Configuration, property prop seems to be wrong
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="prop">
<value>app.properties</value>
</property>
</bean>
According to the Spring documentation
You could use the property location or locations to set the one or multiple values of the properties file.
So the code should be refactored to
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>app.properties</value>
</property>
</bean>
I'm heavily using Spring to develop an application and I was wondering if there's a way to register custom method which can be used when a bean is defined. Currently I'm using ClassPathXmlApplicationContext to load the bean definitions from a XLM file, then in the XML file I would like to do something like
<bean id="bean1" class="..." scope="prototype"
p:some_property='"hello" + #getCorrelativeNumber()/>
Here some_property should then be evaluated to hello0. I know I can register custom functions using StandardEvaluationContext of SpEL, however I can't figure how to make that work in the context of the ApplicationContext.
Any help is greatly appreciated.
Please refer to this blog, look at the section which shows to create an application context in which expressions are used to inject values
<bean id="engine" class="com.baeldung.spring.spel.Engine">
<property name="capacity" value="3200"/>
<property name="horsePower" value="250"/>
<property name="numberOfCylinders" value="6"/>
</bean>
<bean id="someCar" class="com.baeldung.spring.spel.Car">
<property name="make" value="Some make"/>
<property name="model" value="Some model"/>
<property name="engine" value="#{engine}"/>
<property name="horsePower" value="#{engine.horsePower}"/>
</bean>
I have a bean which is used across all projects (different war files).
That particular bean requires a property appname (to know which app is using the bean).
How can i configure this?
I tried passing the value in the following way:
<bean id="appNameProperty" class="java.util.Properties">
<property name="appName" value="app1" />
</bean>
Bean definition:
<bean id="someClass" class="someClass">
<property name="appName" value="#{appNameProperty.appName}" />
</bean>
Where appName is supposed to be a String value.
I get the following exception while deploying my app:
Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'appName' of bean class [java.util.Properties]: Bean property 'appName' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
To avoid the VM arguments you could use the property placeholder configurer as mentioned above. If the app name is fixed for every application and you are using war-files everywhere you could add e.g. "/WEB-INF/config" to the list of the properties location and place there a properties file containing the app-name:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<!-- further locations -->
<value>WEB-INF/config/*.properties</value>
<!-- further locations -->
</list>
</property>
<!-- further configuration as needed -->
</bean>
This may help you.
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchSystemEnvironment" value="true" />
</bean>
<bean id="yourBean" class="path.to.your.BeanClass">
<property name="appName" value="#{systemProperties['appName']}"/>
</bean>
All you need to do is pass VM arguement -DappName=abcApp while starting the app.
ref PropertyPlaceHolderConfigurer
I need a bean like this
<bean id="studentWithSchool" class="com.model.Student" scope="prototype">
<property name="school">
<bean class="com.model.School" scope="prototype"/>
</property>
</bean>
This is OK.
My problem is I have the student returning from a method from a different bean.
I usually load the bean like this when is a property.
<property name='beanProperty' value='#{anotherBean.getBeanProperty()}'/>
But in this case I need the new bean itself being set from the other bean method (School object is returned from another bean method).
This is what I try, and of course this is wrong:
<bean id="studentWithSchool" class="com.model.Student" scope="prototype" value='#{anotherBean.getBeanProperty()}'>
<property name="school">
<bean class="com.model.School" scope="prototype"/>
</property>
</bean>
Is there any workaround?
If I understand you correctly, the studentWithSchool is created and returned by a method in anotherBean. If that's the case, you can use a factory-method:
<bean id="studentWithSchool" factory-bean="anotherBean" factory-method="getBeanProperty" scope="prototype" />
I believe you are trying to use factory patter with Spring . For that you can use factory bean from spring.
<bean id="studentWithSchool" factory-bean="anotherBeanStaticFactory" factory- method="createBeanProperty" scope="prototype"
<property name="school">
<bean class="com.model.School" scope="prototype"/>
</property>
For more detail you can use below link :-
http://docs.spring.io/spring-framework/docs/2.5.6/api/org/springframework/beans/factory/BeanFactory.html
I am trying to set up HostConfiguration bean. One of the property it has is called proxyHost. However, the apache HostConfiguration class does not follow the java beans convention. The setter for the proxyHost accepts an argument of type ProxyHost whereas the getter returns a String.
I have the following snippet in my applicationContext.xml.
<bean id="proxyHost" class="org.apache.commons.httpclient.ProxyHost">
<constructor-arg index="0" type="java.lang.String" value="myproxy.com" />
<constructor-arg index="1" type="int" value="8087" />
</bean>
<bean id="hostConfiguration" class="org.apache.commons.httpclient.HostConfiguration">
<property name="proxyHost" ref="proxyHost" />
</bean>
When I try to load the applicationContext for the app I get the following error since HostConfigurationClass does not have a getProxyHost that returns a ProxyHost or a setter that takes a String:-
org.springframework.beans.NotWritablePropertyExcep tion: Invalid property 'proxyHost' of bean class [org.apache.commons.httpclient.HostConfiguration]: Bean property 'proxyHost' is not writable or has an invalid setter method: Does the parameter type of the setter match the return type of the getter?
While searching on the springsource forum I came across this thread where it was recommended to use MethodInvokingFactoryBean to solve this.
I am not exactly sure how using MethodInvokingFactoryBean would help since I would need a return type of ProxyHost from the method getProxyHost() to fix this, right? And I am not also sure about how to use it in this context. I am not clear on the internals of MethodInvokingFactoryBean. Therefore, if someone could please give me an example in the above context how to use MethodInvokingFactoryBean that would be of immense help.
Also is this generally the accepted way to set up beans like HostConfiguration that do not follow convention in spring?
Thanks!
First , instantiate the ProxyHost
(i.e. ProxyHost proxyHost = new ProxyHost("myproxy1.com",8080);
<bean id="proxyHost" class="org.apache.commons.httpclient.ProxyHost">
<constructor-arg index="0" type="java.lang.String" value="myproxy1.com" />
<constructor-arg index="1" type="int" value="8088" />
</bean>
Then instantiate the HostConfiguration object
(i.e. HostConfiguration hostConfiguration = new HostConfiguration();
<bean id="hostConfiguration" class="org.apache.commons.httpclient.HostConfiguration" />
After that , use the MethodInvokingFactoryBean to call setProxyHost() on the HostConfiguration and pass the proxyHost as argument.
(i.e. hostConfiguration.setProxyHost(proxyHost);)
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject">
<ref local="hostConfiguration"/>
</property>
<property name="targetMethod">
<value>setProxyHost</value>
</property>
<property name="arguments">
<ref local="proxyHost"/>
</property>
</bean>
As mentioned in the other answer you can implement a FactoryBean. If you are using spring 3.0 you could also take a look at the Java Configuration - #Configuration / #Bean.