2

I want to implement some global configuration static class which will contain all the app's configuration. In addition I want to inject these parameters from the xml config file.

The first way is to create config class and inject it to each bean/class I need it. But I don't do it because my config class contains all the app's properties and inject it everywhere is too... I don't know what)

The second way is to try to inject the xml config values to static class but it is more like workaround..

Which way is better and why?

Jakub Hampl
  • 39,863
  • 10
  • 77
  • 106
nKognito
  • 6,297
  • 17
  • 77
  • 138

2 Answers2

1

The most common way I see this type of scenario handled is by placing the configuration into a properties file and referencing the property values via a PropertyPlaceHolderConfigurer.

For instance, say I had the following properties:

SO.properties

app.name=StackOverflow
app.mode=debug

In my Spring configuration file, I would include the context namespace and reference it via a PropertyPlaceholderConfigurer bean.

Spring Configuration

<context:property-placeholder location="classpath:so.properties"/>

After creating the PropertyPlaceholderConfigurer bean I can now reference properties via the expression language such as ${app.name} within beans and the configuration files.

To wire these properties to a Spring bean, annotate a bean's field with @Value.

@Component
public class MyBean{
   //This must be a Spring Bean


   //Wiring the value to the field
   @Value("#{app.name}")
   private String name;
}

PropertyPlaceholderConfigurer Documentation

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • Thanks for your reply. But in this solution the class is not static so I have to initiate it every time I need it... – nKognito Aug 12 '13 at 09:36
0

If I remember correctly you cant do such thing. You can create class with static fields, but you can't inject properties to that fields. Look at this answer, maybe it helps you: Spring: How to inject a value to static field?

Community
  • 1
  • 1
yname
  • 2,189
  • 13
  • 23