Chris Love CNM | Tech Blog



Spring 3 Java Based Configuration with @Value

2 Flares Twitter 0 Facebook 1 Google+ 0 LinkedIn 1 Reddit 0 Made with Flare More Info'> 2 Flares ×

Springsource has released the Javaconfig Framework as a core component of Spring 3.0. There is a trend in the industry to move from XML meta data toward using more annotation driven meta data. I say pick your poison, as one can mess up either.

I do like the readability of using Java code for configuration. Reading the Java classes used for the configuration has a shorter learning curve than reading XML files. Also I can directly unit test my configuration.

The Example

File Highlights

The example code located in on github here. I am using eclipse m2eclipse and spring plugins, and I would recommend importing the project as a maven project.

The Java class used for configuration:

// spring config that loads the properties file
public class AppConfig {

     * Using property 'EL' syntax to load values from the 
     * jetProperties value 
    private @Value("#{jetProperties['']}") String name;
    private @Value("#{jetProperties['jetBean.price']}") Long price;
    private @Value("#{jetProperties['jetBean.url']}") URL url;

     * Create a jetBean within the Spring Application Context
     * @return a bean
    public @Bean(name = "jetBean")
    JetBean jetBean() {
        JetBean bean = new JetBeanImpl();
        return bean;


The highlights for this class:

  • @Configuration – Basic annotation for Java based configuration.
  • @ImportResource – Allows us to import a spring xml file to add more functionality to the configuration that this class is building.
  • @Value – Creates expression driven dependency injection.
  • @Bean – Create a bean managed by the spring container.

The properties-config.xml file:

<beans xmlns=""
  xmlns:xsi="" xmlns:util=""

    <!-- define the properties file to use -->
    <util:properties id="jetProperties" 
        location="classpath:/" />

One line that matters. Line number 8. Create a java.util.Properties instance with values loaded from the supplied properties file.

Other files such as the POJO’s and properties files are included in the example. They are very vanilla, so I did not include them in the post. The test case has some changes in it.

public class JetBeanTest {

    public void testJetBean() {
        // create the spring container using the AppConfig 
        // @Configuration class
        ApplicationContext ctx = 
              new AnnotationConfigApplicationContext(AppConfig.class);
        JetBean jetBean = ctx.getBean(JetBean.class);
        assertThat(jetBean.getName(), equalTo("Gulf Stream G550"));
        assertThat(jetBean.getPrice(), equalTo(Long.valueOf(60000000)));
        URL gulfstream;
        try {
            gulfstream = 
                new URL("");
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            fail("error creating URL");
            throw new RuntimeException("error creating URL");
        assertThat(jetBean.getUrl(), equalTo(gulfstream));

The main change is the new class AnnotationConfigApplicationContext which drives the creation of the Spring application context via Java configuration.


Use @Configuration to annotate your configuration class. Mark your beans with @Bean. The following annotations are supported:

  • @Configuration
  • @Bean
  • @DependsOn
  • @Primary
  • @Lazy
  • @Import
  • @ImportResource
  • @Value

Using @Value with Spring Expression Language

Now starts the crazy cool stuff. The @Value can be used on fields, methods and parameters. Plus, Spring Expression Language (SpEL) defines the ‘value’ through the syntax #{ < SpEL expression > }. The syntax can get a bit harry, but is incredibly powerful. In this example I have used SpEL to load values from the javaProperties java.lang.Properties Object with syntax like:

// jetProperties java.lang.Properties bean in context.
// value in the property file
@Value("#{jetProperties['']}") String name;

Using @Value and SpEL gives you the functionality to do such things as: setting default values, accessing system level properties, logical operators, regex, mathematical operations.

To summarize as Uncle Ben said:

With great power there must come great responsibility.

Link to the example code located in on github here.

Much thanks to Chris Beams and his blog post on Springsource.

· · ·


  • Joshua Holmes · August 17, 2010 at 7:42 pm

    I am doing a huge rewrite on a website from PHP to Java and I started in Spring MVC 2.5, and then moved to 3.0 when it came out… Since my endeavorer into Java one things that has PLAGUED me is finding a good way to handle configurations.

    In .NET we have the al-mighty web.config, and it’s handy pretty easy to use, can’t complain there really. And creating helper classes to interact with it literally took minutes.

    In php I can simply create a file and include it, and this goes for Perl and many other scripting languages, but for some reason, Java on the Web just stayed content with having the poorest config system on the planet for 15+ years.

    I read that in 3.0 there were a lot of new features for config, which put a smile on my face, found your blog and this, so far, is the most straight forward approach I’ve seen yet to reading from a properties file.

    Thanks, I appreciate it!

  • Admin comment by goldgriff · December 20, 2010 at 4:35 am


    My pleasure. Actually been working on some pretty cool injection techniques with passwords recently.


  • Rihards · April 1, 2011 at 6:48 am

    I was looking around for a great tutorial on using the @Value for a while and this is the best one I’ve seen so far.

    Thank you so much, this helped a lot. :)


  • Jacomo · April 7, 2011 at 10:56 pm

    Why does one have to do @ImportResource of a XML file when you’re using all Java config?

    Is there an all Java config method of doing this same thing?

    With Spring 2.5.x I’d written a bean that extended PropertiesLoaderSupport. I’d set that bean’s “locations” to a list of .properties files and it would do the job of loading all given .properties files, in order, into The order was also very important because if any property names in propfile1 were found in propfile2, the values of propfile2 would override the ones in propfile1.

    I’m trying to find an equivalent of this behavior in Spring 3 perhaps using one of their new java config annotations, SpEL, etc.

    Any thoughts?

  • Sani · April 13, 2011 at 7:34 pm


    What if I want to dynamically load value from the property file using EL.

    Something like.

    public void getValue(String propKey){

    String value = @Value(“#{jetProperties['" + propKey +"']}”);


    I know this wont compile but I use it to reflect what im trying to achieve.

    Thanks in advance,

  • Viktor · May 3, 2011 at 6:38 pm

    Thanks! Was really useful!

    It’s notable, that @Value injection can be used not only in @Configuration bean, but in any container-managed bean. That’s definetely much more handy, than the default java.util.Properties!

  • vipul vohra · May 5, 2011 at 3:38 pm

    well done is very helpful to me…can u elobarate @service annotaions too.

  • Admin comment by goldgriff · June 16, 2011 at 5:24 am

    @service annotation are used when you want to mark a bean as a service, and then have the bean loaded into the application context.

  • Admin comment by goldgriff · June 16, 2011 at 5:25 am

    Have not tried that :) That is kinda the direction that I wanted to do another post on.

  • Admin comment by goldgriff · June 16, 2011 at 5:25 am

    That was bugging me as well, but do not have an answer for :(

  • AmitKumar · November 4, 2011 at 6:39 pm

    this is really a great post to explain @Configuration, @Value along with some other handy annotations..

    I developing a web app using these annotations but the beans are not being created.

    do I need to add something to my application-context to make my project @Configuration aware…

    please help…


  • Jinesh Gopinathan · November 28, 2011 at 9:53 pm

    Thanks, The post really helped me. I am new to spring and was experimenting with annotations. I was little confused on importing the properties file. This post really helped me. Thanks.

  • Roberto Lebeau · January 17, 2012 at 4:13 am

    I really like and appreciate your article post. Fantastic.

  • Revolução Java - Artigos, Tutoriais, Livros e Dicas atualizadas sobre o Mundo Java! · June 12, 2012 at 1:25 am

    [...] The Java class used for configuration: ? [...]

  • Suraj · November 3, 2012 at 12:59 pm

    Hi, I have a small question
    Here Iam injecting values to the colors

    List colors;

    Similay I want to inject value to the map,where my key and values will be hardcoded in the java file it self

    String[][] countries =
    {{“United States”, “New York”},
    {“United Kingdom”, “London”},
    {“Netherlands”, “Amsterdam”},
    {“Japan”, “Tokyo”},
    {“France”, “Paris”}};

    Map capitals;

    How to i Do that?

  • Volodymyr · January 4, 2013 at 3:59 pm

    Spring 3.1 adds @PropertySource annotation, which simplifies the life

  • Eric Jablow · April 1, 2013 at 9:01 pm

    Usually, you should not catch exceptions. Remove the try-catch, keep the new URL call on line 14 and 15, and simply declare the method as throwing MalformedURLException. Don’t change the @Test annotation though. This way, if the URL is malformed, JUnit will see the unexpected exception, and call it a test failure.

Leave a Reply



2 Flares Twitter 0 Facebook 1 Google+ 0 LinkedIn 1 Reddit 0 2 Flares ×