Execute a Method When a Bean Is Created
As we mentioned previously, one way to receive the initialization callback is to designate a method on
your bean as an initialization method and tell Spring to use this method as an initialization method. As
discussed, this callback mechanism is useful when you have only a few beans of the same type or when
you want to keep your application decoupled from Spring. Another reason for using this mechanism is
to enable your Spring application to work with beans that were built previously or were provided by
third-party vendors.
Specifying a callback method is simply a case of specifying the name in the init-method attribute of
a bean's <bean> tag. Listing 5-1 shows a basic bean with two dependencies.:
Listing 5-1. The SimpleBean Class
package com.apress.prospring3.ch5.lifecycle;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class SimpleBean {
private static final String DEFAULT_NAME = "Luke Skywalker";
private String name = null;
private int age = Integer.MIN_VALUE;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void init() {
System.out.println("Initializing bean");
if (name == null) {
System.out.println("Using default name");
name = DEFAULT_NAME;
}
if (age == Integer.MIN_VALUE) {
throw new IllegalArgumentException(
"You must set the age property of any beans of type " + SimpleBean.class);
}
}
public String toString() {
return "Name: " + name + "\nAge: " + age;
}
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home