Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorthand for creating a String constant in Spring context XML file?

Tags:

java

spring

I need to define a string value in Spring context XML file that is shared by multiple beans.

This is how I do it:

<bean id="aSharedProperty" class="java.lang.String">     <constructor-arg type="java.lang.String" value="All beans need me :)"/> </bean> 

Creating a java.lang.String bean by passing a constructor argument of java.lang.String seems kludgy.

Is there a shortcut?

I know this property can be passed using PropertyOverrideConfigurer, but I want to keep this property within the XML file.

like image 948
akirekadu Avatar asked Apr 16 '12 22:04

akirekadu


People also ask

What is the XML file name used in Spring xml configuration?

The name of that XML is simply adding "-servlet" after the name of the dispatcher servlet. So according to the above configuration in web. xml spring will load dispatcher-servlet. xml file from WEB-INF directory of the project.

What is context xml in Spring?

Applicationcontext. xml - It is standard spring context file which contains all beans and the configuration that are common among all the servlets. It is optional file in case of web app. Spring uses ContextLoaderListener to load this file in case of web application. Spring-servlet.

Which is better annotation or xml in Spring?

From my own experience annotations better than xml configuration. I think in any case you can override xmls and use annotations. Also Spring 4 give us a huge support for annotations, we can override security from xml to annotations e.t.c, so we will have not 100 lines xml but 10 lines Java Code.

Can we use xml configuration in Spring boot?

Spring allows you to configure your beans using Java and XML.


1 Answers

You can use PropertyPlaceholderConfigurer and keep values in xml:

<context:property-placeholder properties-ref="myProperties"/>  <bean id="myProperties"      class="org.springframework.beans.factory.config.PropertiesFactoryBean">   <property name="properties">     <props>       <prop key="aSharedProperty">All beans need me :)</prop>     </props>   </property> </bean> 

Then you reference it with:

<bean id="myBean" class="my.package.MyClass">   <property name="someField" value="${aSharedProperty}"/> </bean> 
like image 100
mrembisz Avatar answered Sep 17 '22 09:09

mrembisz