del.icio.us Digg DZone Reddit StumbleUpon
Software Development

Spring Paranoia with InitializingBean and Assert

Ensure that your beans are properly initialized using InitializingBean and Assert.

In this (very) quick article, I'm going to show you how to use the InitializingBean interface and the Assert utility class, both part of the Spring Framework, to express any deep-seated feelings of initialization paranoia you may have.

Let's just jump right in with a code example.

package com.example.user.service;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.Assert;

import com.example.user.dao.UserDao;

public class UserServiceImpl implements UserService, InitializingBean {
    private UserDao userDao;
    private JavaMailSender mailSender;

    public void setUserDao(UserDao userDao) {
        Assert.notNull(userDao, "userDao can't be null"); // 1
        this.userDao = userDao;
    }

    public void setMailSender(JavaMailSender mailSender) {
        Assert.notNull(mailSender, "mailSender can't be null"); // 2
        this.mailSender = mailSender;
    }

    public void afterPropertiesSet() {
        Assert.notNull(userDao, "userDao required"); // 3
        Assert.notNull(mailSender, "mailSender required");
    }

    ...service methods...
}

In the example above, we have a hypothetical user service with two dependencies: a DAO and a mail sender. The idea here is that we want to do some sanity checks as we initialize our service bean. First, when setting the user DAO, we want to make sure that we don't set it to a null value 1. We conduct the same test for the mail sender 2. In each case we use the Spring Assert utility class to perform the test. (Be sure not to confuse this with the assert keyword from the Java language, or the JUnit class of the same name.)

Finally, we implement the single method required by the InitializingBean interface, afterPropertiesSet. Here we check to see that all required properties have actually been set 3. If they haven't, then Spring complains. Compliant BeanFactory implementations call the afterPropertiesSet method as part of the standard bean lifecycle; see the BeanFactory Javadocs for more information.

This technique is handy for being sure that your dependency injections actually happen. This is especially useful when using autowiring, where it's easy to miss the fact that some required injection didn't actually occur.

You can use InitializingBean and Assert for any Spring-managed bean, not just service beans. I've just used a service bean here as an example.

Obviously, if you use the InitializingBean interface then you tie your bean APIs to the Spring Framework. You'll have to decide whether that's something you can live with. With Assert, on the other hand, you're only building in an implementation dependency on Spring, which is less objectionable. (It may still be a minor nuisance if you were to decide to move away from Spring, but nothing you couldn't easily handle. I'd probably say the same thing of using InitializingBean in this case, incidentally.)

Anyway, now you know the pros and cons of the approach. Have fun!

Social bookmarks: del.icio.us Digg DZone Reddit StumbleUpon

Comments (5)

Hey Willie,

a quite conservative approach would be to use constructor injection. Even if there null values could be given, too. Instead of InitializingBean I prefer using @Required as (1) annotations could be switched of during compilation or you could (b) provide you own annotation you tell the BeanPostProcessor to ensure properties being set on.

Regarding the Assert it also depends. I tend to use it in classes that intrinsically depend on Spring anyway or at least have a good reason to depend on it. The alternative would do the check manually or provide your own wrapping utility class that uses the Spring Assert internally.

Regards,
Ollie
By Oliver Gierke on Oct 28, 2008 at 1:54 PM PDT
I'm afraid the information in this article is about 2 years out-of-date. Since Spring 2.5 the easiest way to ensure that dependencies are injected is simply to annotate the relevant data member with @Resource("myBean"), where 'myBean' refers to the name of the bean that should be injected. If 'myBean' does not exist an exception is thrown at startup
By Donal on Oct 28, 2008 at 3:20 PM PDT
When using Spring 2.5, I prefer annotating constructor (natural class initializer) with @Autowired, which by default treats dependencies as required; also this like @Resource approach removes need for dependency setter/mutator and minimizing mutability is good (see Effective Java 2nd edition, Item 15). With @Autowired, like with InitializingBean, one is more tied to Spring, but I prefer it to @Resource, because even though @Autowired supports wiring by name it supports, and in my opinion is primarily intended to be used for, wiring by type; @Resource can only wire by name. @Autowired, combined with @Component, @Service, and @Repository can make your spring context files very manageable. Nice introductory text on use of both @Resource and @Autowired can be found at http://www.infoq.com/articles/spring-2.5-part-1
By Stevo Slavic on Oct 29, 2008 at 6:35 PM PDT

he myth of pandora is ancient, appears in several distinct Greek versions, pandora armbandand has been interpreted in many ways. In all literary versions, Neu Eingetroffen however, Pandora Armbänder the myth is a rosetta stone kind of theodicy, addressing the question pop information, web easy get, sports fashion, news-fashionof why there is evil in the world. In the seventh hot-winter century BC, Hesiod, both in his Theogony (briefly, without naming Pandora outright rosetta stone language, rosetta stone spanish, abercrombie and fitch, Abercrombie Fitch

By pandora schmuck on Aug 30, 2010 at 10:59 PM PDT

The Pandora pandora schmuck myth first Pandora Armreifenappears in lines Pandora Halsketten of Hesiod's poem in Pandora Charms epic meter, the Theogony (ca. 8th?7th centuries BC), without ever giving the woman a name. After humans Pandora Sets have received thethe myth is a rosetta stone kind of theodicy, addressing the question pop information, web easy get, sports fashion, news-fashionof why there is evil in the world. In the seventh hot-winter century BC, Hesiod, both in his Theogony (briefly, without naming Pandora outright rosetta stone language, rosetta stone spanish, abercrombie and fitch, Abercrombie Fitch

By pandora schmuck on Aug 30, 2010 at 11:51 PM PDT

Post a comment

Your name:
Your e-mail address (won't be displayed):
Your web site (optional):
example: www.xyz.com
Your comment:
Preview:
By You
Please help us reduce comment spam:
Spring in Practice
My brother and I are writing Spring in Practice for Manning!

What's New?

2009-08-30 - Check out my two-part series on DZone: Spring Integration: A Hands-On Tutorial.
2009-03-25 - My new article Getting Started with Spring Batch 2.0 is available on DZone.
Home | Consulting | Tech Articles | Mailing List | Contact | Spring Blog
Copyright © 2008 Wheeler Software, LLC.