Datasheet
log4j.rootLogger=FATAL, first
log4j.appender.first=org.apache.log4j.ConsoleAppender
log4j.appender.first.layout=org.apache.log4j.PatternLayout
log4j.appender.first.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
Wiring Beans Automatically by Type
In the preceding example you wired the properties of the CalculateSpring bean explicitly. In practice,
you can actually ask the Spring container to automatically wire up the properties. The next “Try It Out”
shows how to perform automatic wiring.
Try It Out Autowire by Type
Automatic wiring can save you some work when you’re creating context descriptors. Basically, when
you tell the Spring container to autowire, you’re asking it to find the beans that fit together. This can
be done automatically by the container without you providing explicit instructions on how to wire the
beans together. There are many different ways to autowire, including by name, by type, using the con-
structor, or using Spring’s autodetection. Each of these will be described in a bit. For now, let’s discuss
the most popular type of autowiring, autowiring by type.
Autowiring by type means that the container should try to wire beans together by matching the required
Java class and/or Java interface. For example, a
CalculateSpring object can be wired with an instance
of
Operation (Java interface) type, and an instance of ResultWriter (Java interface) type. When told to
autowire by type, the Spring container searches the context descriptor for a component that implements
the
Operation interface, and for a component that implements the ResultWriter interface.
This feature can be a time-saver if you are creating a large number of beans in a context descriptor.
To try out autowiring by type with the
CalculateSpring project, follow these steps:
1. Change the directory to the src/springfirst/target/classes directory:
cd src/chapter1/springfirst/target/classes
2. You should see beans.xml here. Maven 2 has copied the context descriptor here during compi-
lation. Modify the
beans.xml context descriptor, as shown in the following listing; the changed
lines are highlighted. Note that you need to remove the lines not shown in the listing.
<?xml version=”1.0” encoding=”UTF-8”?>
<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd”>
<bean id=”screen” class=”com.wrox.begspring.ScreenWriter” />
<bean id=”add” class=”com.wrox.begspring.OpAdd” />
<bean id=”opsbean” class=”com.wrox.begspring.CalculateSpring” autowire=”byType” />
</beans>
14
Chapter 1: Jump Start Spring 2
01612c01.qxd:WroxPro 10/31/07 10:42 AM Page 14