How to load configuration parameters from XML files into Spring MVC Controllers? - java

I've noticed that I can load a config parameter into a bean using something like this in application-context.xml:
<beans:bean id="foo" class="com.foo.FooBean">
<beans:property name="foo" value="${foo}" />
</beans:bean>
What about if I want to access the foo value in a Controller without instantiating a bean? Is there a way to do that?

You can use the #Value annotation with util:properties
<util:properties id="props" location="classpath:com/foo/bar/props.properties"/>
And in your controller class, assuming you have a property with key 'foo':
#Value("#{props.foo}")
public void setFoo(String foo) {
this.foo = foo;
}

You can use PropertyPlaceholderConfigurer
Please refer to this link to read more about it
http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/beans.html#beans-factory-placeholderconfigurer

Related

Populate spring bean property using annotations only, at run-time

I have a bean Parent with just one property attr.
class Parent
{
String attr;
public void doStuff(){
//stuff
}
public String getAttr() {
return attr;
}
public void setAttr(String attr) {
this.attr=attr;
}
}
I have three beans that extend this Parent bean.
My spring.xml looks like this-
<bean id="parent" class="Parent"/>
<bean id="child1" parent="parent">
<property name="attr" value="Sample value 1"/>
</bean>
<bean id="child2" parent="parent">
<property name="attr" value="Sample value 2"/>
</bean>
<bean id="child3" parent="parent">
<property name="attr" value="Sample value 3"/>
</bean>
I want to do the same thing using annotations.
Problem is that I have to do this storefront and all the beans in my controller are declared as -
#Resource
#Qualifier("child1")
Parent child1;
Is there a way I can add the property to the child beans using annotations or any other approach in controller i.e. without using spring.xml?
Is there a way of doing this using the #Value annotation. Problem is that I don't have a static value that comes from a property file. I have 3 different value for 3 different beans.
Shouldn’t this work, if you have three different values in your properties file
see post here
#Value(“${child1.attr}”)
#Value(“${child2.attr}”)
#Value(“${child3.attr}”)

Spring #Value is always null

I'm using spring in my app and I have a .properties file which has some values defined.
In a java class there is a String value:
#Value("${test}")
public String value;
The point is that if I inject this value in beans definition:
<bean id="customClass" class="package.customClass.CustomClassImpl">
<property name="value" value="${test}"></property>
</bean>
It works fine, but if I use #Value, there is always a null... Why is that happening?
And no, I'm not doing any "new" no instantiate "customClass", I get it with context.getBean("customClass).
EDIT: I have configured a property placeholder in the context:
<bean id="properties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config.properties</value>
<value>classpath:constants.properties</value>
</list>
</property>
</bean>
Thanks in advance.
Remember, your class need a stereotype annotation like #Component or #Service
If you are creating spring boot application and your goal is to provide configuration parameter(s) via (application).properties there is a way to do it without explicit #Value declaration.
Create YourClassProperties with annotation #ConfigurationProperties("some.prefix"):
#ConfigurationProperties("my.example")
public class MyClassProperties {
private String foo;
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
}
Add defined properties to (application).properties:
my.example.foo=bar
And then, in your application you can autowire needed properties...
#Autowired
private MyClassProperties myClassProperties;
... and use them as you would any other properties:
LOG.info("Value of the foo: {}", myClassProperties.getFoo());
Solve, you need to enable annotation config in configuration file: <context:annotation-config/>
You need to declare your .properties file using #PropertySource. Not sure it's doable using xml config.
Also, are you sure about this "$", it's "#" in this example :
http://forum.spring.io/forum/spring-projects/container/61645-value-and-propertyplaceholderconfigurer

Spring Di via setter dynamic constructor parameters

I'm beginner with spring framework, and I'm following this tutorial to applicate DI via setter. All works fine, but I'd like add to my class CsvOutputGenerator a constructor with one dynamic parameter, passed on the fly while I getting bean from Application context.
How can I do that?
I've already change my spring configuration in this way:
...
<bean id="CsvOutputGenerator" class="com.mkyong.output.impl.CsvOutputGenerator">
<constructor-arg type="java.lang.String" value="Test"/>
</bean>
...
but in this way is static value for my constructor.
You can pass it via system property for example
<constructor-arg lazy-init="true" type="java.lang.String" value="#{ systemProperties['some.key']}"/>
Try something else, even though Spring isn't made to be used like this (note the "prototype" scope):
<bean id="CsvOutputGenerator" class="com.mkyong.output.impl.CsvOutputGenerator" scope="prototype" />
And then in your code you can do something like this:
CsvOutputGenerator myBean = (CsvOutputGenerator) context.getBean("CsvOutputGenerator", "testing testing");
This is the method in the API that I used above.
The below content is based on the above question and comments.
Say u have a class URLRepo with attribute String url. url is initialized to value.
Then you can do something like this, to wire your CsvOutputGenerator
public class URLRepo {
private String url = "your value";
getters and setters
}
<bean id="urlRepo" class="com.*.*.MyURLRepo"/>
<bean id="CsvOutputGenerator" class="com.mkyong.output.impl.CsvOutputGenerator">
<constructor-arg type="java.lang.String" value="urlRepo.url"/>
</bean>
hope this is what you are looking for.

Spring: Inject URL for classpath resource

I want to inject the URL of a classpath resource in a way that does not create a dependency on Spring in the Bean. Meaning, the bean should not use Spring's interfaces/classes. How can I do that?
Spring is able to convert classpath:... values into java.net.URL implicitly:
public class Foo {
private URL url;
...
}
.
<bean class = "Foo">
<property name = "url" value = "classpath:..." />
</bean>
Following on from axtavt's answer, if you will allow yourself Spring annotations in the bean, you can do it like this:
#Value("classpath:myClasspathLocation") private URL url;
create your own implementation of a spring resource by extending the org.springframework.core.io.ClassPathResource like MyClasspathResource extends ClassPathResource and inject this type into your bean. Like this you do not have any dependency to spring and can later reimplement your resource with something else.
<bean class="myBean">
<property name="classPathType">
<bean class="org.test.bla.MyClasspathResource">
<constructor-arg index="0" value="classpath:/org/test/bla/MyUrl" />
</bean>
</property>
</bean>
There is hardly anything non-spring that's equivalent to Spring's resource concept.
You could for example use Guava's InputSupplier as an alternative, but you are missing powerful standard spring features if you do.

How can I inject a property value into an annotation configured spring mvc 3.0 controller

First: I'm using Spring 3.0
I have a problem when configuring my controller class. The controller uses a web service which I want to define the endpoint address using a .properties file.
#Controller
public class SupportController {
#Value("#{url.webservice}")
private String wsEndpoint;
...
In my application context xml-file, I've defined this:
<context:property-placeholder location="/WEB-INF/*.properties" />
I've been reading the documentation, trying different approaches (like adding prefix systemProperties.),but I keep getting an error message telling me that it doesn't exist.
Field or property 'url' cannot be
found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext'
Ok. I've figured it out.
Now, in the controller:
#Value("#{settings['url.webservice']")
Then in the context configuration I have this "helper bean":
<util:properties id="settings"
location="/WEB-INF/supportweb.properties"></util:properties>
This should work, too:
#Value("${url.webservice}")
private String wsEndpoint;
I have this configuration and it works fine:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:application.properties</value>
</list>
</property>
</bean>
and I iniejct the property in this way
#Value("${root.log.level}")
private String prop;
the field is correctly initialized to "DEBUG" value.
you should check that the
<context:property-placeholder location="/WEB-INF/*.properties" />
is defined in webmvc-config.xml where you create instances of the #Controllers

Categories

Resources