Listing 7-33. Configuring an AspectJ Aspect
<?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-3.1.xsd">
<bean id="aspect" class="com.apress.prospring3.ch7.aspectj.MessageWrapper"
factory-method="aspectOf">
<property name="prefix">
<value>Ha Ha!</value>
</property>
<property name="suffix">
<value>Ho Ho!</value>
</property>
</bean>
</beans>
As you can see, much of the configuration of the aspect bean is very similar to standard bean
configuration. The only difference is the use of the factory-method attribute of the <bean> tag. The
factory-method attribute is intended to allow classes that follow a traditional Factory pattern to be
integrated seamlessly into Spring. For instance, if you have a class Foo with a private constructor and then
a static factory method, getInstance(), using factory-method allows a bean of this class to be managed by
Spring. The aspectOf() method exposed by every AspectJ aspect allows you to access the instance of the
aspect and thus allows Spring to set the properties of the aspect. Listing 7-34 shows a simple driver
application for this example.
Listing 7-34. AspectJ Configuration in Action
package com.apress.prospring3.ch7.aspectj;
import org.springframework.context.support.GenericXmlApplicationContext;
public class AspectJExample {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:aspectj.xml");
ctx.refresh();
MessageWriter writer = new MessageWriter();
writer.writeMessage();
writer.foo();
}
}
Notice that first we load the ApplicationContext to allow Spring to configure the aspect. Next we
create an instance of MessageWriter and then invoke the writeMessage() and foo() methods. The output
from this example is as follows:
Ha Ha!
foobar!
Ho Ho!
foo
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home