CDI是否适用于常规Java应用程序?

时间:2014-08-20 04:12:45

标签: java cdi

我有三个类的简单maven项目。在我META-INF我的空beans.xml。每次我运行Main.java时,我都会获得NullPointerException

Exception in thread "main" java.lang.NullPointerException
at hom.World.helloWorld(World.java:12)
at hom.Main.main(Main.java:6)

我想要完成的工作是否超出了CDI的范围?

Hello.java

package hom;
import javax.enterprise.inject.Default;

@Default
public class Hello {
   public String hello() {
      return "Hello ";
   }
}

World.java

package hom;
import javax.enterprise.inject.Default;
import javax.inject.Inject;

@Default
public class World {
   @Inject
   Hello hello;

   public String helloWorld() {
      return hello.hello() + "World!";
   }
}

Main.java

package hom;
public class Main {
   public static void main(String[] args) {
      World helloWorld = new World();
      System.out.println(helloWord.helloWorld());
   }
}

2 个答案:

答案 0 :(得分:10)

可以在独立应用程序中使用CDI。

Weld weld = new Weld();
WeldContainer container = weld.initialize();
World helloWorld = container.instance().select(World.class).get();
System.out.println(helloWorld.helloWorld());
weld.shutdown();

您还需要焊接依赖。

<dependency>
    <groupId>org.jboss.weld.se</groupId>
    <artifactId>weld-se-core</artifactId>
    <version>2.2.4.Final</version>
</dependency>

另请参阅有关该主题的Weld documentation

答案 1 :(得分:1)

以下示例适用于CDI 2。

Left

依赖性相同。

myButton

我们使用<dependency> <groupId>org.jboss.weld.se</groupId> <artifactId>weld-se-core</artifactId> <version>3.1.2.Final</version> </dependency> package com.zetcode; import com.zetcode.provider.HelloMessageProvider; import com.zetcode.renderer.ConsoleMessageRenderer; import com.zetcode.renderer.MessageRenderer; import javax.enterprise.inject.se.SeContainer; import javax.enterprise.inject.se.SeContainerInitializer; public class CdiSimple { public static void main(String[] args) { SeContainerInitializer initializer = SeContainerInitializer.newInstance(); try (SeContainer container = initializer.disableDiscovery() .addBeanClasses(HelloMessageProvider.class, ConsoleMessageRenderer.class).initialize()) { MessageRenderer messageRenderer = container.select(ConsoleMessageRenderer.class).get(); messageRenderer.render(); } } } 在Java SE上设置CDI。

SeContainerInitializer

这是SeContainer

package com.zetcode.provider;

public interface MessageProvider {

    String getMessage();
}

这是MessageProvider

package com.zetcode.provider;

public class HelloMessageProvider implements MessageProvider {

    public String getMessage() {

        return "Hello there";
    }
}

这是HelloMessageProvider

package com.zetcode.renderer;

public interface MessageRenderer {

    void render();
}

最后是MessageRenderer