Rich Web Experience

JSFOne

Private Events

Blogs

View all Blogs >>
  • Venkat Subramaniam

    Founder of Agile Developer, Inc.

    I got an email from Dan Sline about the upcoming Houston Techfest. more»

  • Stuart Halloway

    CEO of Relevance

    This is Part Two of a series of articles on Java.next. In Part Two, I will look at how Java.next languages interoperate with Java. more»

  • Andrew Glover

    Co-author of "Continuous Integration"

    more»

  • Neal Ford

    Application Architect at ThoughtWorks, Inc.

    I was talking to my friend Brian Goetz recently, and he reminded me of more»

  • Craig Walls

    Author of Spring in Action

    I've been scanning the early draft of OSGi R4.2, specifically RFC 124, "A Compo more»

  • John Heintz

    Principal Consultant with New Aspects of Software

    In a recent discussion interview questions came up, here's my favorite one.To set some context this question is designed to gauge the abst more»

  • Scott Leberknight

    Chief Architect at Near Infinity

    In almost every application I've done, the database tables have some kind of audit trail fields. Sometimes this is a separate "audit log"... more»

  • Alex Miller

    Sr. Engineer with Terracotta Inc.

    It’s time again for my monthly music club mix. This month is a bit of indulgent power pop and just a smattering of stuff I’ve... more»

  • Nathaniel Schutta

    Author, speaker, software engineer focused on user interface design.

    Recently, I sat through some vendor presentations and while I won’t name names, I just have to say: learn to give better talks. If I... more»

  • Matt Raible

    Creator of AppFuse and author of Spring Live

    The developers of Seam have come up with a list of major issues with JSF. I'm assuming many more»

  • Jared Richardson

    Agile coach and co-author of Ship It

    The first scheduled class for the NFJS One venture is now official! And we don't even have the website live yet. :) This class will be a go... more»

  • Pratik Patel

    Enterprise Architect

    A fine fellow by the name of Srini came to my talk on JPA at the NoFl more»

  • Michael Nygard

    Agile technology leader and dynamicist

    A short while back, I did a brief series on the value of "d more»

  • Richard Haefel

    VP of Developer Relations, Curl Inc.

    more»

  • Kenneth Kousen

    President of Kousen IT, Inc.

    A couple of weeks ago I participated in a BriefingsDirect podcast about using more»

  • Ted Neward

    Enterprise, Virtual Machine and Language Wonk

    As Joel points out, we've made a draft of the S more»

  • Jason Rudolph

    Author of Getting Started with Grails

    As we’ve seen over the last several weeks, it’s remarkably easy for code to earn the badge of 100% more»

  • Erik Doernenburg

    Principal Consultant @ Thoughtworks

    The Spring framework has become ubiquitous in the Java world, and there are a large number of to more»

  • Mike Levin

    Software Developer specializing in Web2.0 websites

    more»

  • Ryan Shriver

    Business and Technology Consulting

    more»

  • Mark Johnson

    Director of Consulting at CGI

    At the Columbus NFJS show held on July 25-27th during one of the BOF sessions Dave Bock, Scott Davis and I discussed unit tests vs functional... more»

  • Joseph Nusairat

    Author of Beginning JBoss Seam & Co-Author of Beginning Groovy & Grails

    Well i am assuming Apress has the most random site in the world at times.But today only they have our recent book, Beginning Groovy & Grai more»

  • Jeff Brown

    G2One Director Of North American Operations - Groovy and Grails Developer

    We are really excited to have a 3 day Groovy/Grails training event coming up in Chicago later this month. The training dates are August... more»

  • Brian Pontarelli

    Brian Pontarelli - founder of Inversoft

    I went to the 37 Signals event last night sponsored by CPB. The speake more»

  • Graeme Rocher

    Project Lead of the Grails Project & CTO of G2One

    I'll be giving a talk on the state of Grails at the London Groovy+Grails user group meeting on the 31st of July. more»

  • Keith Donald

    Lead of Spring Web and Creator of Spring Web Flow

    I am pleased to announce that Developing Rich Web Applications with Spring, a three-day bootcamp lead by SpringSource engineers on web... more»

  • Pramod Sadalage

    Co-author of "Refactoring Databases:Evolutionary Database Development"

    When creating a Foreign Key constraint on the database as shown below ALTER TABLE BOOK ADD (CONSTRAINT FK_BOOK_ more»

  • Vladimir Vivien

    Software Engineer / Consultant

    Judging from the list of features that will be included in NetBeans 6.5, more»

  • David Bock

    Principal Consultant, CodeSherpas Inc.

    I just spent this weekend speaking at the Ag ile IT Exchange conference i more»

  • Kirk Knoernschild

    Software Developer & Mentor

    I’ve published a summary of the OSGi survey results on the APS blog more»

  • Brian Goetz

    Author of Java Concurrency in Practice

    This surprised the heck out of me.  We recently finished a new TV room down in the basement.  We have a 50″ plasma TV, mounted on the... more»

  • Jason Harwig

    Senior Software Engineer at Near Infinity

    I was reading a blog entry at more»

  • Pete Behrens

    Organizational Agility Coach

    Marti nig & Associates Methods & Tools group recentl more»

  • Brian Sam-Bodden

    Java author, Ruby geek and Open Source Advocate

    In this installment we are going to build the Dashboard page of the Tempo application. T more»

  • Mark Fisher

    Spring Integration Lead

    In my recent post, I had mentio more»

  • Ron Bodkin

    Chief Software Architect, Quantcast

    I'm looking forward to speaking at The Rich Web Experience conference in San Jose next month. The event runs from September 7th through 9th.... more»

  • Mark Goodwin

    Web Application Security Specialist

    We've already looked at one of the two big problems posed by anti DNS pinning on Java applets; because there's rebinding on the applet and... more»

  • Scott Davis

    Author of "Groovy Recipes" & TDD Expert

    Every time I see a live show at the Denver Botanic more»

  • Romain Guy

    Java User Interface expert.

    more»

  • Ramnivas Laddad

    Author of AspectJ in Action, Principal at SpringSource

    InfoQ.com has published my AOP myths and realities talk recorded at a No Fluff Just Stuff conference. InfoQ.com founded by Floyd Marine more»

  • David Geary

    Author of Graphic Java and co-author of Core JSF

    The 2006 NFJS tour kicked off t more»

  • Howard Lewis Ship

    Creator of Tapestry and HiveMind

    <p> Just spent many minutes on a wild goose chase and the underlying cause was that I had a &lt;div&gt; and a... more»

  • Kito Mann

    Editor-in-chief of JSF Central and the author of JSF in Action

    This article explains how to implement the sorting feature of the dataTable component of the JavaServer Faces Widget Library, which is... more»

  • Jason Hunter

    Author of Java Servlet Programming

    I just posted the JDOM 1.1 release for download. This release includes about 20 improvements and bug fixes. more»

Just How Does Spring Do Its Classpath Component Scanning Magic?

Posted by: Scott Leberknight on 06/23/2008

One really cool feature in Spring 2.5+ is classpath component scanning. For example, instead of manually defining and wiring up all the beans comprising your Spring-based application, you simply add a few "driver" snippets of XML to your application context configuration, and then annotate your component classes with @Component (or any specialization such as @Controller and @Service). I am calling the XML snippets a "driver" because all they do is enable a specific feature, such as classpath scanning or component autowiring:

<-- Enable autowiring via @Autowire annotations -->
<context:annotation-config/>

<-- Scan for components in a package (and its subpackages)  -->
<context:component-scan base-package="org.springframework.samples.petclinic.web"/>

After seeing this was pretty cool, I wanted to know how exactly they did the classpath scanning. It boils down to doing some gymnastics with class loaders and resource path matching and using the ClassLoader.getResources(String name) method which returns an Enumeration containing URLs representing classpath resources. Those resources (Java classes) are then checked to see if they contain the @Component annotation (or a specialization of it) and if so, are considered a "candidate" component. Other filtering can take place but by default those components are then defined programmatically as Spring beans. When annotation configuration is enabled, autowiring of components also takes place, so I can have Spring scan the classpath for all my web controllers, and then automatically inject dependencies such as services or data access objects. Cool!

The actual classes that perform this magic are the ClassPathScanningCandidateComponentProvider which, by default, uses a PathMatchingResourcePatternResolver to find matching classpath resources using ClassLoader.getResources(). As a quick example, you can see this in action by writing a simple script, like so:

ClassPathScanningCandidateComponentProvider provider =
    new ClassPathScanningCandidateComponentProvider(true);
String basePackage = "org/springframework/samples/petclinic";
Set<BeanDefinition> components = provider.findCandidateComponents(basePackage);
for (BeanDefinition component : components) {
    System.out.printf("Component: %s\n", component.getBeanClassName());
}

Running this code (using the PetClinic sample application shipped with Spring), you get the following output:

Component: org.springframework.samples.petclinic.hibernate.HibernateClinic
Component: org.springframework.samples.petclinic.jdbc.SimpleJdbcClinic
Component: org.springframework.samples.petclinic.jpa.EntityManagerClinic
Component: org.springframework.samples.petclinic.web.AddOwnerForm
Component: org.springframework.samples.petclinic.web.AddPetForm
Component: org.springframework.samples.petclinic.web.AddVisitForm
Component: org.springframework.samples.petclinic.web.ClinicController
Component: org.springframework.samples.petclinic.web.EditOwnerForm
Component: org.springframework.samples.petclinic.web.EditPetForm
Component: org.springframework.samples.petclinic.web.FindOwnersForm

For a more fun experiment, I tried to scan using "org" as the base package...

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at org.springframework.asm.ClassReader.a(Unknown Source)
	at org.springframework.asm.ClassReader.(Unknown Source)
	at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76)
	at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:68)
	at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCandidateComponents(ClassPathScanningCandidateComponentProvider.java:181)
	at org.springframework.samples.petclinic.ClassPathScannerTester.main(ClassPathScannerTester.java:17)

Ok, so you need to restrict the scan space that Spring will use or else you could run out of memory scanning every possible class in your system! Regardless, with classpath scanning of components and autowiring of dependencies, you can cut down the amount of XML in Spring-based apps a lot.


  • Currently 2.0/5
  • 1
  • 2
  • 3
  • 4
  • 5
2.0 rating out of 3 votes


About Scott Leberknight

Scott is Chief Architect at Near Infinity Corporation, an enterprise software development, training, and consulting services company based in Reston, Virginia. He has been developing enterprise and web applications for over 13 years professionally, and has developed applications using Java, Ruby/Rails, Groovy/Grails and Python. His main areas of interest include object-oriented design, system architecture, testing, and frameworks of all types including Spring, Hibernate, Ruby on Rails, Grails, and Django. In addition, Scott enjoys learning new languages to make himself a better and more well-rounded developer a la The Pragmatic Programmers' advice to "learn one language per year."

Scott holds a B.S. in Engineering Science and Mechanics from Virginia Tech, and an M. Eng. in Systems Engineering from the University of Maryland. Scott speaks at the No Fluff Just Stuff Symposiums and various other conferences. In his (sparse) spare time, Scott enjoys spending time with his wife, two daughters, and two cats. He also tries to find time to play soccer, go snowboarding, and mountain bike whenever he can.

More About Scott »