2015-04-05 1 views
4

я использовал,EJB и CDI инъекционные точки в @FacesValidator и @FacesConverter не в состоянии работать с помощью OmniFaces новых версий JSF

  • Mojarra 2.3.0-M01
  • OmniFaces 2.0.
  • PrimeFaces 5,1 окончательный
  • PrimeFaces Extension 3.0.0
  • GlassFish Сервер 4,1

и другие артефакты Java EE.


Инъекции точки в @FacesValidator вроде как следует,

@FacesValidator(value="testValidator") 
public class TestValidator implements Validator { 

    @Inject 
    private DemoEJB ejb; 

    @Inject 
    private ManagedBean managedBean; 

    @Override 
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { 
     // Use the injected EJB and/or managed bean here. 
    } 
} 

Эти точки инъекции остаются null (я явно не попробовать нагнетание EJB, но это не должно происходить так же, как управляемый компонент).


Поскольку вышеупомянутый версия Mojarra все еще доступен как снимок, я попытался понижая его 2.2.10 с той же версией OmniFaces, которая является 2,0 (альтернативно, также пытались с OmniFaces 2.1-SNAPSHOT - на обоих Mojarra 2.2.10 и 2.3.0-m01), но безрезультатно.

Это сработало, когда я понизил Majarra до 2.2.8-02 (попробовал с OmniFaces 1.8.1, 2.0 и 2.1-SNAPSHOT в качестве альтернативы). Я не пробовал другие версии Моджарры.

была поддержка, чтобы сделать @FacesValidator и @FacesConverter кандидатов на EJB и точек впрыска CDI с помощью OmniFaces (который, в свою очередь, не требует каких-либо зависимостей сложения и/или конфигурации) удалены для новых версий Mojarra?

я еще не явно пытался в @FacesConverter только потому, что изменение этого много библиотек в качестве альтернативы так много раз, используя IDE NetBeans багги, который также идет очень медленно на Windows, по своей природе взял весь день от рассвета до заката.


EDIT:

Сервер производит следующие Сварные связанные предупреждения.

WARN: WELD-001700: Interceptor annotation class javax.ejb.PostActivate not found, interception based on it is not enabled 
WARN: WELD-001700: Interceptor annotation class javax.ejb.PrePassivate not found, interception based on it is not enabled 
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] private org.glassfish.jersey.gf.cdi.internal.CdiComponentProvider.processAnnotatedType(@Observes ProcessAnnotatedType<Object>) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds. 
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] public org.omnifaces.VetoAnnotatedTypeExtension.processAnnotatedType(@Observes ProcessAnnotatedType<Object>) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds. 
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] public org.glassfish.jms.injection.JMSCDIExtension.processAnnotatedType(@Observes ProcessAnnotatedType<Object>) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds. 
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] org.glassfish.sse.impl.ServerSentEventCdiExtension.processAnnotatedType(@Observes ProcessAnnotatedType<Object>, BeanManager) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds. 
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] private org.glassfish.jersey.gf.cdi.internal.CdiComponentProvider.processAnnotatedType(@Observes ProcessAnnotatedType<Object>) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds. 
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] private org.glassfish.jersey.gf.cdi.internal.CdiComponentProvider.processAnnotatedType(@Observes ProcessAnnotatedType<Object>) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds. 
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] public org.glassfish.jms.injection.JMSCDIExtension.processAnnotatedType(@Observes ProcessAnnotatedType<Object>) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds. 
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] public org.glassfish.jms.injection.JMSCDIExtension.processAnnotatedType(@Observes ProcessAnnotatedType<Object>) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds. 
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] public org.omnifaces.VetoAnnotatedTypeExtension.processAnnotatedType(@Observes ProcessAnnotatedType<Object>) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds. 
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] org.glassfish.sse.impl.ServerSentEventCdiExtension.processAnnotatedType(@Observes ProcessAnnotatedType<Object>, BeanManager) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds. 
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] public org.glassfish.jms.injection.JMSCDIExtension.processAnnotatedType(@Observes ProcessAnnotatedType<Object>) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds. 
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] org.glassfish.sse.impl.ServerSentEventCdiExtension.processAnnotatedType(@Observes ProcessAnnotatedType<Object>, BeanManager) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds. 
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] org.glassfish.sse.impl.ServerSentEventCdiExtension.processAnnotatedType(@Observes ProcessAnnotatedType<Object>, BeanManager) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds. 
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] private org.glassfish.jersey.gf.cdi.internal.CdiComponentProvider.processAnnotatedType(@Observes ProcessAnnotatedType<Object>) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds. 
WARN: WELD-001473: javax.enterprise.inject.spi.Bean implementation [email protected] declared a normal scope but does not implement javax.enterprise.inject.spi.PassivationCapable. It won't be possible to inject this bean into a bean with a passivating scope (@SessionScoped, @ConversationScoped). This can be fixed by assigning the Bean implementation a unique id by implementing the PassivationCapable interface. 
WARN: WELD-001473: javax.enterprise.inject.spi.Bean implementation [email protected] declared a normal scope but does not implement javax.enterprise.inject.spi.PassivationCapable. It won't be possible to inject this bean into a bean with a passivating scope (@SessionScoped, @ConversationScoped). This can be fixed by assigning the Bean implementation a unique id by implementing the PassivationCapable interface. 
WARN: WELD-001473: javax.enterprise.inject.spi.Bean implementation [email protected] declared a normal scope but does not implement javax.enterprise.inject.spi.PassivationCapable. It won't be possible to inject this bean into a bean with a passivating scope (@SessionScoped, @ConversationScoped). This can be fixed by assigning the Bean implementation a unique id by implementing the PassivationCapable interface. 
WARN: WELD-001473: javax.enterprise.inject.spi.Bean implementation [email protected] declared a normal scope but does not implement javax.enterprise.inject.spi.PassivationCapable. It won't be possible to inject this bean into a bean with a passivating scope (@SessionScoped, @ConversationScoped). This can be fixed by assigning the Bean implementation a unique id by implementing the PassivationCapable interface. 
WARN: WELD-001473: javax.enterprise.inject.spi.Bean implementation [email protected] declared a normal scope but does not implement javax.enterprise.inject.spi.PassivationCapable. It won't be possible to inject this bean into a bean with a passivating scope (@SessionScoped, @ConversationScoped). This can be fixed by assigning the Bean implementation a unique id by implementing the PassivationCapable interface. 
WARN: WELD-001473: javax.enterprise.inject.spi.Bean implementation [email protected] declared a normal scope but does not implement javax.enterprise.inject.spi.PassivationCapable. It won't be possible to inject this bean into a bean with a passivating scope (@SessionScoped, @ConversationScoped). This can be fixed by assigning the Bean implementation a unique id by implementing the PassivationCapable interface. 
+0

Работает для меня на Tomcat 8.0.18 + Mojarra 2.3.0-m01 (и 2.2.10) + Weld 2.2.9. У меня сейчас нет GF4.1, но с какой версией Weld он поставляется? – BalusC

+0

Версия Weld в GlassFish 4.1 является 2.2.2, как указано [здесь] (https://blogs.oracle.com/theaquarium/entry/spotlight_on_glassfish_4_16) и [здесь] (http://nofluffjuststuff.com/blog/reza_rahman/ 2014/09/spotlight_on_glassfish_4_1__9_components_versions). Несмотря на то, что я не знаю, есть ли способ получить этот номер версии программно. GlassFish 4.1 выпускает некоторые предупреждения, связанные с Weld. Я приложил их к вопросу. – Tiny

+0

Версия для сварки зарегистрирована как 'INFO: WELD-000900'. Я понизил его до 2.2.2 для Tomcat, но все равно не могу воспроизвести его. Должен попробовать GF 4.1 позже. Эти предупреждения маловероятны. – BalusC

ответ

6

Это связано с изменением Mojarra 2.2.9. Он отлично работает в 2.2.8. Я воспроизвел его как в GlassFish 4.1, так и в WildFly 8.2. После сканирования всех проблем, перечисленных в 2.2.9 release notes и связанных с ними пулах изменений, это, как представляется, является следствием обратного порта issue 3552 для JSF 2.2.x. Они внутренне не проверяли возможность инъекции компонентов, поведения, валидаторов и преобразователей, которые неявно регистрировали их как кандидатов, управляемых CDI. Другими словами, в период 2.2.x до 2.2.9 Моджарра непреднамеренно предложил «родную» поддержку @Inject в упомянутых артефактах.

Для того, чтобы получить инъекцию в @FacesConverter и @FacesValidator работать в любом случае через OmniFaces, вам нужно добавить пустой /WEB-INF/beans.xml или, по крайней мере, один с bean-discovery-mode набором для all вместо annotated.

<?xml version="1.0" encoding="UTF-8"?> 
<beans 
    xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:weld="http://jboss.org/schema/weld/beans" 
    bean-discovery-mode="all" 
> 
    <!-- ... --> 
</beans> 

Это значение по умолчанию уже, вы также можете просто опустить атрибут bean-discovery-mode.

Техническое отличие заключается в том, что bean-discovery-mode="all" зарегистрирует все правомочных классы как CDI управляемых компонентов, в то время как bean-discovery-mode="annotated" регистрирует только классы с явным КДИ области видимости аннотации, такие как @RequestScoped, как КДИ управляемом бобы, которые, таким образом, терпеть неудачу для @FacesConverter и @FacesValidator.

+0

Для подхода JSF 2.3 требуется дополнительный атрибут 'managed = true' в аннотации класса, чтобы вызвать его. См. Также http://jdevelopment.nl/jsf-23/ – BalusC

+0

Обязательно использовать bean-discovery-mode = "all". Будет ли это работать, если я пометю Validator с аннотацией к области видимости? Будет ли работать @ RequestScoped или @ Dependent? – guest

+1

@guest К сожалению, маркировка bean-компонента с помощью аннотации, определяющей bean-компонент, тоже не сработает.Вы можете понизить свои JSF-файлы до версии с поддержкой «инъекций» Mojarra, используя шаги, описанные в http://stackoverflow.com/questions/17085717/upgrade-jsf-mojarra-in-jboss-as-eap-wildfly. Потому что bean-discovery-mode = "all" отстой. – jpangamarca

Смежные вопросы