Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define a string in spring context

Tags:

spring

I have three (A,B,C) spring context.xml, A is for the basic configuration, B and C import the A.

In a bean on A I have:

<bean class="com.example.Ex">
    <property name="aString" value="${myString}" />
</bean>

now I want to define the property myString on B and C context, is possible to do it without create and loads two different properties file?

like image 226
rascio Avatar asked Jul 11 '11 15:07

rascio


People also ask

How do you define spring context?

The 'context' in the spring framework is shorthand for "ApplicationContext", which is the programming construct that the framework uses to access components from the Inversion-of-Control container where they are cached.

What are contexts in spring boot?

The Application Context is Spring's advanced container. Similar to BeanFactory, it can load bean definitions, wire beans together, and dispense beans upon request.

What is context configuration in Spring MVC?

@ContextConfiguration defines class-level metadata that is used to determine how to load and configure an ApplicationContext for integration tests.


2 Answers

You could try an alternative way by declaring bean of type String, instead of dealing with Properties.

This way:

A

<bean class="com.example.Ex">
    <property name="aString" ref="str" />
</bean>

And then you declare in your B and C contexts the "str" reference this way:

B

<bean id="str" class="java.lang.String">
  <constructor-arg value="string_1"/>
</bean>

C

<bean id="str" class="java.lang.String">
  <constructor-arg value="string_2"/>
</bean>
like image 142
Mr.Eddart Avatar answered Sep 30 '22 14:09

Mr.Eddart


For completeness here another way of creating a string:

Instead of calling the String constructor which forces a new object to be created unnecessarily it may be a better idea to use the valueOf method which can here serve as a "do nothing" constructor:

<bean id="str" class="java.lang.String" factory-method="valueOf">
  <constructor-arg value="string_1"/>
</bean>

However this is only academic as the overhead of parsing the additional XML attribute which will cause strings to be created as well may be greater than the performance gain of calling valueOf instead of the constructor.

like image 31
yankee Avatar answered Sep 30 '22 14:09

yankee