Get ahead
VMware offers training and certification to turbo-charge your progress.
Learn moreYesterday, Joris and I gave a session at the Dutch Java Users Group. We did the session twice and had about 250 people in total attending the sessions. A lot of people asked for the code for the demos we did during the sessions. Attached you'll find the code for the AOP and Dependency Injection demos. It shows a simple aspect flushing the Hibernate session before every JDBC operation (not as robust as you'd want it in production code, but it's a start) and it also shows the CarPlant system (demo'd before in other sessions and previously attached to another blog entry) configured using the various to do Dependency Injection in Spring 2.1 (i.e. using <bean>, @Bean and @Autowired).
It's a Maven2 project, so you'll need to have Maven2 installed. To prepare an Eclipse project including all libraries, run mvn eclipse:eclipse at the command line in the carplant directory.
The sources: carplant.zip
During the session a question came up about multiple <aop:config> blocks inside one application contexts. The guy in the audience wasn't sure if two or more blocks of AOP configuration showed the expected result (advising two or more times). I don't have the guys email address, so I wanted to clarify this here a little bit. Consider the following code. The doIt() will be advised. The actual advice (for simplicity) is kept in the same class, just as the main method bootstrapping the ApplicationContext.
public class Logger {
public void doIt() {
}
public void log() {
System.out.println("Log!");
}
public static void main(String args[]) {
ApplicationContext context =
new ClassPathXmlApplicationContext(
new String[] {"com/carplant/context1.xml", "com/carplant/context2.xml"});
Logger logger = (Logger)context.getBean("logger");
logger.doIt();
}
}
<bean id="logger" class="Logger"/>
<aop:config>
<aop:pointcut id="doItOperation" expression="execution(* doIt(..))"/>
<aop:aspect ref="logger">
<aop:before pointcut-ref="doItOperation" method="log"/>
</aop:aspect>
</aop:config>
As expected, upon calling the doIt() method we'll only get one line of output from the logger (it's only advised once).
<bean id="logger" class="Logger"/>
<aop:config>
<aop:pointcut id="doItOperation" expression="execution(* doIt(..))"/>
<aop:aspect ref="logger">
<aop:before pointcut-ref="doItOperation" method="log"/>
</aop:aspect>
</aop:config>
<aop:config>
<aop:pointcut id="doItOperation2" expression="execution(* doIt(..))"/>
<aop:aspect ref="logger">
<aop:before pointcut-ref="doItOperation2" method="log"/>
</aop:aspect>
</aop:config>
Running this will also show that the bean will be advised twice.
Note that I'm using a 2.1 milestone release here.