Learn Java for Web Development

(Tina Meador) #1

210 CHAPTER 5: Building Java Web Applications with Spring Web MVC


Listing 5-6. Configuring Dependency Through Setter-Based DI






The tag defines a property for dependency injection. Listing 5-6 can be translated into
the Java code illustrated in Listing 5-7.


Listing 5-7. Java Code Equivalent of Listing 5-6


ClassA classA = new ClassA();
ClassB classB = new ClassB();
classA.setClassB(classB);


Tip Constructor-based and setter-based DI can be used simultaneously, but it is recommended to use
constructor arguments for mandatory dependencies and setters for optional dependencies.

The Spring container is essentially a factory that creates objects encapsulating the creation of
objects and configures these objects using the configuration metadata that contains information
about the collaborating objects in the application that must be created. Spring provides two types of
IoC container implementation.


   Bean factories (defined by the org.springframework.beans.factory.
BeanFactory interface)
 Application contexts (defined by the org.springframework.context.
ApplicationContext interface)

Bean factories are the simplest of containers and provide basic support for DI. ApplicationContext
is a subinterface of BeanFactory that provides application framework services, such as the following:


   The ability to resolve textual messages from a properties file
 The ability to publish application events to interested event listeners
 The application-layer specific contexts such as the WebApplicationContext to be
used in the web tier

Note Web applications have their own WebApplicationContext. The WebApplicationContext
will be explained when we discuss web-based Spring applications later in this chapter.
Free download pdf