My question is how does JSF implementation find all classes annotated with @ManagedBean? Does it scan all of the classes in the class path? Or is there a way to actually "query" the JVM for the annotated classes?
Start by peeking around in com.sun.faces.application.annotation.AnnotationManager
in Mojarra sources. Note that this is not part of the API, but implementation-specific.
If you intend to use such tools for your own projects, I recommend using Google Reflections for this instead of homegrowing it.
Set<Class<?>> classes = reflections.getTypesAnnotatedWith(SomeAnnotation.class);
Update to clarify: to have JSF to load any annotated managed beans from a JAR file, you have to put a /META-INF/faces-config.xml
file in the JAR file. Just a JSF 2.0 compatible <faces-config>
declaration is sufficient to get the JSF scan the JAR file for any interesting annotated classes. If the /META-INF/faces-config.xml
file is not present in the JAR file, then JSF won't scan the JAR file to improve loading performance.
Here's how a minimum JSF 2.0 compatible faces-config.xml
file can look like:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
</faces-config>
Store it in the META-INF
folder of the JAR.
This is by the way described in chapter 11.4.2 of JSF 2.0 specification.
11.4.2 Application Startup Behavior
...
This algorithm provides considerable flexibility for developers that are assembling the components of a JSF-based web
application. For example, an application might include one or more custom UIComponent implementations, along with
associated Renderers, so it can declare them in an application resource named “/WEB-INF/faces-config.xml”
with no need to programmatically register them with Application instance. In addition, the application might choose
to include a component library (packaged as a JAR file) that includes a “META-INF/faces-config.xml” resource.
The existence of this resource causes components, renderers, and other JSF implementation classes that are stored in this
library JAR file to be automatically registered, with no action required by the application.