Notes for registering bean defs at runtime

When registering bean definitions at runtime via BeanDefinitionRegistryPostProcessor or the alike, always set the AbstractBeanDefinition.setResourceDescription(String). It will be shown you on the kilometre long exception reports when everything fails, thus helping you debug it. Even the following will tear less hair from your head:

private void registerFoo(String beanName, BeanDefinitionRegistry registry) {
  GenericBeanDefinition def = new GenericBeanDefinition();
  def.setBeanClassName("foo.bar.Foobar");
  def.setResourceDescription(toString()); // or getClass().getName()
  registry.registerBeanDefinition(beanName, def);
}

The above will result in:

Exception in thread “main” org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [foo.bar.Foobar] for bean with name ‘foo’ defined in your-toString(); …

Instead of:

Exception in thread “main” org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [foo.bar.Foobar] for bean with name ‘foo’ defined in null; …

I first thought that it might be nicer to define beans in straight java, but I’ve now realized it gets more trickier (and non-obvious); save yourself and just do it the plain xml style!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: