java – JSF如何找到用@ManagedBean註釋的bean?
據我所知,對於在C#中使用@Annotations(或[Attributes]),您必須對類元資料進行引用,以便您可以詢問該類是否已註釋(歸因).
我的問題是JSF實現如何使用@ManagedBean來註釋所有類?它是否掃描類路徑中的所有類?還是有一種方法來實際上“查詢”JVM的註釋類?
我問這個是因為當我把註釋的支援bean直接放在我的Web專案中時,沒有問題.但是我在JAR檔案中定義的bean(可跨專案可重用)未註冊.有沒有什麼我必須告訴MyFaces來指導哪個JAR檔案要看?
此外,使用註釋引入了許多不錯的程式設計模式.我想知道我是否可以找到所有註釋的類…
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?
從ofollow,noindex" target="_blank">Mojarra
年的
com.sun.faces.application.annotation.AnnotationManager
年開始.請注意,這不是API的一部分,而是實現特定的.
如果您打算為自己的專案使用這些工具,我建議您使用Reflections 而不是自己的專案.
Set<Class<?>> classes = reflections.getTypesAnnotatedWith(SomeAnnotation.class);
在Java EE環境中,更好的是使用CDI.
I’m asking this because when I put my annotated backing beans in my web project directly, there’s no problem. But the beans that I define in the JAR files (to be reusable across projects) are not registered. Is there something that I have to tell MyFaces to direct it which JAR files to look at?
要使JSF從JAR檔案載入任何帶註釋的託管bean,必須將/META-INF/faces-config.xml檔案放在JAR檔案中.只是一個JSF 2.0相容<faces-config>宣告足以使JSF掃描JAR檔案以獲取任何有趣的註釋類.如果/META-INF/faces-config.xml檔案不存在於JAR檔案中,則JSF將不會掃描JAR檔案以提高載入效能.
以下是與JSF 2.0相容的最少的faces-config.xml檔案如下所示:
<?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>
將其儲存在JAR的META-INF資料夾中.
這是按照JSF 2.0 specification 第11.4.2章的描述.
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”
In addition, the application might choose
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.
也可以看看:
http://stackoverflow.com/questions/3717376/how-does-jsf-find-beans-annotated-with-managedbean