Java Reference
In-Depth Information
Listing 5-6. Configuring Dependency Through Setter-Based DI
<bean id="classA" class="ClassA">
<property name="classB" ref="classB" />
</bean>
<bean id="classB" class="ClassB" />
The <property> 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.
org.springframework.beans.factory.
Bean factories (defined by the
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
WebApplicationContext to be
The application-layer specific contexts such as the
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.
 
Search WWH ::




Custom Search