Java Reference
In-Depth Information
Where should you make a call to the openFile() method for initialization? In Java, the initialization
tasks should be performed in the constructor. But would it work here if you call the openFile() method
in the default constructor of the Cashier class? No, because the openFile() method requires both the
name and path properties to be set before it can determine which file to open.
public class Cashier {
public void openFile() throws IOException {
File logFile = new File( path, name + ".txt");
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(logFile, true)));
When the default constructor is invoked, these properties have not been set yet. So you may add a
constructor that accepts the two properties as arguments, and call the openFile() method at the end of
this constructor. However, sometimes you might not be allowed to do so, or you might prefer to inject
your properties via setter injection. Actually, the best time to call the openFile() method is after all
properties have been set by the Spring IoC container.
Implementing the InitializingBean and DisposableBean Interfaces
Spring allows your bean to perform initialization and destruction tasks in the callback methods
afterPropertiesSet() and destroy() by implementing the InitializingBean and DisposableBean
interfaces. During bean construction, Spring will notice that your bean implements these interfaces
and call the callback methods at a suitable time.
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class Cashier implements InitializingBean, DisposableBean {
public void afterPropertiesSet() throws Exception {
public void destroy() throws Exception {
Now if you run your Main class again, you will see that a checkout record is appended to the text file
c:/cashier/cashier1.txt . However, implementing such proprietary interfaces will make your beans
Spring-specific and thus unable to be reused outside the Spring IoC container.
Setting the init-method and destroy-method Attributes
A better approach of specifying the initialization and destruction callback methods is by setting the
init-method and destroy-method attributes in your bean declaration.
Search WWH ::

Custom Search