2013-05-08 45 views
0

這是我第一次嘗試CDI。我有一個Eclipse Kepler環境,我有一個部署在內部Glassfish 4.0運行時的Maven Web項目。CDI不工作

它有一個servlet和一個JAX-RS資源POJO,它們都可以正常工作。接下來,我在同一個包作爲servlet和JAX-RS POJO創建了一個類:

package com.example.test; 

import java.util.logging.Logger; 

import javax.enterprise.context.ApplicationScoped; 
import javax.enterprise.inject.Produces; 

@ApplicationScoped 
public class Bean { 

    @Produces @ApplicationScoped 
    public static Bean produce() { 
    return new Bean(); 
    } 

    public Bean() { 
    Logger.getGlobal().info("Bean()"); 
    } 

} 

,我修改了POJO:

package com.example.test; 

import javax.annotation.Resource; 
import javax.inject.Inject; 
import javax.ws.rs.GET; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 

@Resource(name = "foo", type = Rest.class) 
@Path("/rest") 
public class Rest { 

    @Inject Bean b; 

    @GET 
    @Produces("text/html") 
    public String f() { 
    return "<h1>rest</h1>"; 
    } 
} 

當我訪問POJO的其餘路徑我得到的消息在Glassfish日誌中:

WARNING: StandardWrapperValve[com.younum.web.test.App]: Servlet.service() for servlet com.example.test.App threw exception 
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=Bean,parent=Rest,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,1573724652) 

當我嘗試訪問POJO時,這也顯示爲網頁上的異常。

我在做什麼錯?我覺得某個Web項目不會觸發CDI,我不確定將其轉換爲Java EE項目需要什麼。 pom.xml如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 
    <groupId>com.younum.web</groupId> 
    <artifactId>test</artifactId> 
    <version>0.0.1-SNAPSHOT</version> 
    <packaging>war</packaging> 
</project> 

回答

2

正是有了與Eclipse開普勒M6捆綁版本的GlassFish的問題。當我使用獨立的Glassfish 4.0-b87時,它工作正常。

4

在META-INF文件夾中需要beans.xml文件。 默認情況下,CDI在我們部署項目時未啓用或激活。所以要激活它,我們需要beans.xml文件,它應該位於meta-inf文件夾下。

下面的beans.xml

<beans 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/beans_1_0.xsd"> 
</beans> 

樣本這裏是一個很好的鏈接,開始 http://oppansource.blogspot.in/2013/05/cdi-in-nutshell.html

+1

嗯,不太正確,但upvoted,因爲它的幫助。該標準允許beans.xml的多個位置。玻璃魚可能是越野車。 – necromancer 2013-05-08 06:40:03

相關問題