What’s in my Spring Context?

When we are learning Spring, there are times we are not sure which beans are in the Spring context. Especially when we use convenient features of Spring 3 such as <context:annotation-driven/> or <context:component-scan/>. As developers, we want to inspect the classes that are automatically registered providing the opportunity to look at the source code and javadocs to see what each class does.


JUnit Tests get Application Context

Our JUnit tests have the ability to inject the Application Context. This is one of the many benefits of @RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(value = "/META-INF/spring/test-app-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class BeansInContextTest {

     @Autowired
     ApplicationContext applicationContext;

Simple Code

Let’s loop through all the beans that are defined or discovered with the following code.

@Before
public void setup() {
  logger.debug("********************");
  String[] beans = applicationContext.getBeanDefinitionNames();
  for (String o : beans) {
    logger.debug("________________________");
    logger.debug("BEAN = " + o);
    logger.debug("\tType = " + applicationContext.getType(o));
    String[] aliases = applicationContext.getAliases(o);
     if (aliases != null && aliases.length > 0) {
       for (String a : aliases) {
         logger.debug("\tAliased as: " + a);
       }
     }
  }

  logger.debug("********************");
  logger.debug("*** Number of Beans = {} ***",
    applicationContext.getBeanDefinitionCount());
  logger.debug("********************");
  }
}

What is the Alias?

We can define beans with “id” which by XML law requires it to be unique per file. This restricts us in the ability to use special symbols for the name should we want to. I recommend using “id” unless absolutely necessary. However, should we what to refer to the bean with multiple names or use special symbols, we can use the “name” attribute. By comma separating the tokens, we have the opportunity to refer to a bean with any of the tokens provided.

<bean name="mailServer/default, mailServer" class="..."/>

If no, “id” is provided, the first token becomes the primary and the subse quent tokens become aliases. Does this matter in the usage of the beans? No. But to find “all” the names of the beans, we would display the aliases in addition to the bean names.

The Full Test Code

package com.gordondickens.sample;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@ContextConfiguration(value = "/META-INF/spring/test-app-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class BeansInContextTest {
  private final Logger logger = LoggerFactory
    .getLogger(BeansInContextTest.class);

  @Autowired
  ApplicationContext applicationContext;

  @Before
  public void setup() {
    logger.debug("********************");
    String[] beans = applicationContext.getBeanDefinitionNames();
    for (String o : beans) {
      logger.debug("________________________");
      logger.debug("BEAN = " + o);
      logger.debug("\tType = " + applicationContext.getType(o));
      String[] aliases = applicationContext.getAliases(o);
      if (aliases != null && aliases.length > 0) {
        for (String a : aliases) {
          logger.debug("\tAliased as: " + a);
        }
      }
    }
   
    logger.debug("********************");
    logger.debug("*** Number of Beans = {} ***",
      applicationContext.getBeanDefinitionCount());
    logger.debug("********************");
  }
}

Sample Bean Context

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd


http://www.springframework.org/schema/context

      http://www.springframework.org/schema/context/spring-context-3.0.xsd">

  <context:annotation-config/>

  <bean id="myBean" class="MyCoolBean"/>

</beans>

Experiment and Have Fun

Add beans to the config file. Import other config files and see what happens.

About Gordon

Technology enthusiast primarily focused on Java and Open Source projects. Spring Certified Professional and Trainer. http://twitter.com/gdickens http://linkedin.com/in/gordondickens http://github.com/gordonad
This entry was posted in Spring and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>