簡體   English   中英

如何將HK2 DI框架與Jersey 2配合使用?

[英]How to use HK2 DI framkework with Jersey 2?

我正在嘗試在球衣中使用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>

所以我認為有些錯誤。

  1. 注入的類型必須是“合約”類型,如bind(Impl).to(Contract) to(Contract)指定要注入的“廣告”類型。

    因此,與其嘗試注入PropertiesHandlerImpl ,不如注入合同PropertiesHandler

     @Inject PropertiesHandler handler; 
  2. 我看不到您如何使用JDBCConnectionStrategy 它沒有在您的AbstractBinder配置,所以我猜您只是在自己實例化它。 這行不通。 您還需要將其連接到DI系統並注入。

  3. 施工后進行現場注入。 因此,除非將服務注入到構造函數中,否則不能使用該服務。

     @Inject public JDBCConnectionStrategy(PropertiesHandler handler) { } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM