Gordon Dickens is an instructor, mentor & consultant. Gordon is currently architecting and teaching several official SpringSource courses and actively tweets about open source technology at http://twitter.com/gdickens. Gordon is active within the Spring Framework community focussed on: Spring training, Spring Roo, Spring Integration, Spring Batch and Eclipse Virgo OSGi projects. Gordon is a DZone MVB and is not an employee of DZone and has posted 39 posts at DZone. You can read more from them at their website. View Full User Profile

What’s in my Spring Context?

04.20.2011
| 14137 views |
  • submit to reddit

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.chariot.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.

Wanna Learn More?

Learn more about what goes on Spring Context by attending a Core Spring Training class at Chariot.

 

From http://gordondickens.com/wordpress/2011/04/19/whats-in-my-spring-context/

Published at DZone with permission of Gordon Dickens, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: