Java 7独立应用程序中的依赖注入 [英] Dependency Injection in a Java 7 standalone application

查看:83
本文介绍了Java 7独立应用程序中的依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在大型Java 7独立应用程序中使用依赖项注入,但是我不确定从哪里开始.

I would like to use dependency injection in a large Java 7 standalone application, but I am not really sure where to start.

我编写了一个小型测试应用程序:

I have written a small test application:

public class Main {

    @Inject
    MyInterface myInterface;

    public static void main( String[] args ) {

        Main m = new Main();
        System.out.println(m.myInterface.getMessage());

    }

}

具有界面:

public interface MyInterface {

    String getMessage();

}

和接口实现:

@Singleton
public class MyInterfaceImpl implements MyInterface {

    public String getMessage() {
        return "Hello World!";
    }

}

pom.xml包含一个依赖项:

<dependencies>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

此应用程序可以编译,但是,当尝试打印消息时,它当然会以NPE崩溃.注射没有发生.

This application compiles, but of course, it crashes with a NPE when trying to print the message. The injection has not happened.

所以,我的问题是:

  1. 可以在Java 7独立应用程序中实现依赖项注入吗?
  2. 我还必须包括哪些其他依赖项才能使其正常工作?
  3. 有人能分享一个简单的操作示例(我找不到)吗?

推荐答案

不仅有一种在Java中使用依赖项注入的方法.

There is not only one way to use dependency injection with Java.

(1)例如,您可以使用标准CDI,其中参考实现为 Weld .有关于在Java SE中使用焊接的文档环境独立应用程序可能是什么意思.

(1) You could for instance use the standard CDI, where the reference implementation is Weld. There is documentation about using Weld in a Java SE environment, what is probably what you mean by standalone application.

您也可以使用 Spring框架,该框架还支持通用的CDI注释(例如@Inject).在这种情况下,您通常会创建一个

You could alternatively also use Spring Framework, which also supports the common CDI annotation (e.g. @Inject). In this case, you will typically create a ClasspathXmlApplicationContext at the program startup and let Spring manages (create/destroy) all the beans you need.

(2)您当前的依赖项仅导入Java EE的API.因此,如果您在执行过程中得到NullPointerException,我并不感到惊讶.您需要添加一个实现(例如Weld)或使用Spring.

(2) You current dependencies only imports the API of Java EE. Thus I'm not surprised if you get a NullPointerException at the execution. You need to add an implementation (like Weld) or use Spring.

(3)参见上面的链接.

(3) See links above.

还请参见 Java EE 6 CDI实现之间的区别以获取有关其他Java CDI可用实现的参考.

Also take a look at Differences between Java EE 6 CDI Implementations to get reference about other Java CDI available implementations.

这篇关于Java 7独立应用程序中的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆