Thursday, June 18, 2009

Spring MVC bean lookup

Once defined a bean in xml file, you can inject to other beans or look up by other beans.
Inject is kind of easy as it is defined in bean xml file.

With bean name, we can look at it up. Here is the utils for it
First defined itself in xml file


Second defined in Java file.

public class BeanLookupService
extends ApplicationObjectSupport
{


private static ApplicationContext mApplicationContext;

/**
* @see org.springframework.context.support.ApplicationObjectSupport#initApplicationContext()
*/
protected void initApplicationContext()
throws BeansException
{
mApplicationContext = getApplicationContext();
}

/**
*


* Returns the bean specified in the beanName parameter. The bean must be
* configured in the application context xml file. If the bean is not found,
* null is returned.
*


* @param beanName -
* the name of the bean find in the application context.
* @throws NoSuchBeanDefinitionException -
* when the beanName is not found in the application context.
* @return the bean specified in the beanName parameter or null if the bean is
* not found.
*/
public static Object getBean( final String beanName )
throws NoSuchBeanDefinitionException
{

if ( mApplicationContext == null ) {
sLogger.info( "application context is null" );
return null;
}

return mApplicationContext.getBean( beanName );
}

/**
*
*


* Get Application context
*


* @return application context
*/
public static ApplicationContext getAppContext() {
return mApplicationContext;
}
}