【问题标题】:How to use HK2 DI framkework with Jersey 2?如何在 Jersey 2 中使用 HK2 DI 框架?
【发布时间】:2017-01-10 17:06:18
【问题描述】:

我正在尝试在球衣中使用 hk2 DI,并且我已经阅读了一些关于此事的文本。 (我认为大多数都过时了) 目前我有一个扩展 ResourceConfig 的类:

public class MyApplication extends ResourceConfig{
    public MyApplication(){
        register(new AbstractBinder() {
            @Override
            protected void configure() {
                bind(AuthenticationServiceImpl.class).to(AuthenticationService.class);
                bind(PropertiesHandlerImpl.class).to(PropertiesHandler.class).in(Singleton.class);
            }
        });
        packages(true, "com.myclass");        }
}

在另一个类中,我尝试注入其中一个绑定类:

public class JDBCConnectionStrategy implements DatabaseConnectionStrategy {
    private Connection connection;

    @Inject
    PropertiesHandlerImpl propertiesHandler;

    public JDBCConnectionStrategy() throws SQLException{
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            String host = propertiesHandler.getProperty("host");
            String userName = propertiesHandler.getProperty("userName");
            String password = propertiesHandler.getProperty("password");
            //Create a connection
            this.connection = DriverManager.getConnection(host, userName, password);
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
....
}

这样声明:

@Singleton
@Service
public class PropertiesHandlerImpl implements PropertiesHandler {...}

问题:启动应用时出现以下错误

WARNING: The following warnings have been detected: WARNING: Unknown HK2 failure detected:
MultiException stack 1 of 2 java.lang.NullPointerException
    at com.myclass.JDBCConnectionStrategy.<init>

更新
我应该补充一下,我将应用程序包添加到web.xml中的扫描路径:

    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>com.myclass.system.CmisApplication</param-value>
    </init-param>

【问题讨论】:

  • 我发现一件事有误,但犹豫是否将其发布为答案,因为我在您的帖子中的任何地方都没有看到问题陈述。 究竟您面临的问题是什么(例如错误/堆栈跟踪/异常)?
  • @peeskillet 例如,当使用注入的 propertiesHandler 时,我得到一个 NullPointerException
  • @Service 仅在您使用一种自动方法向 hk2 告知您的服务时才有效。要使用自动方法,您可能需要调用类似hk2.java.net/2.5.0-b31/apidocs/org/glassfish/hk2/utilities/… 的方法。一般来说,请阅读此页面以获取有关自动服务填充的信息:hk2.java.net/2.5.0-b31/…

标签: java dependency-injection jax-rs jersey-2.0 hk2


【解决方案1】:

所以我看到了一些问题。

  1. 注入的类型需要是“合约”类型,如bind(Impl).to(Contract)to(Contract) 指定应该注入的“广告”类型。

    因此,与其尝试注入 PropertiesHandlerImpl,不如注入合约 PropertiesHandler

    @Inject
    PropertiesHandler handler;
    
  2. 我不知道您如何使用JDBCConnectionStrategy。它没有在你的AbstractBinder 中配置,所以我猜你只是在自己实例化它。这行不通。您还需要将其连接到 DI 系统并注入它。

  3. 字段注入发生在构造之后。所以你不能在构造函数中使用服务,除非你将它注入到构造函数中。

    @Inject
    public JDBCConnectionStrategy(PropertiesHandler handler) {
    
    }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 2014-11-01
    • 2016-10-14
    • 1970-01-01
    相关资源
    最近更新 更多