0

SpringとJavaを同時に学んでいます。私は自分のアプリケーションコンテキストに取り組んでいます。これが私の豆の1つです:

package com.example.app.context;

@Configuration
public class ApplicationContextConfiguration {

    @Bean
    public ComboPooledDataSource comboPooledDataSource() {
        // ... setup pool here
        return pool;
    }
}

今、私はこのBeanを使いたいです:

package com.example.db.queries;

import javax.inject.Inject;

public class DatabaseQueries {

    @Inject private ComboPooledDataSource comboPooledDataSource;

    public static List<Records> getData() {
        Connection connection = comboPooledDataSource.getConnection();
        // ... create sql query and execute 
} 

しかし、コンパイル時に次のエラーが発生します。

[ERROR] non-static variable comboPooledDataSource cannot be referenced from a static context

この Bean にアクセスするにはどうすればよいですか?

事前に感謝します。覚えておいてください、私は学んでいます!

4

2 に答える 2

3

あなたのメソッドgetData()は静的です。Spring を使用する場合、または一般的に依存性注入を使用する場合は、静的メソッドを以前よりもはるかに少なく使用します。非静的にします。DatabaseQueries を使用する必要がある場合は、再度注入します。

@Component
public class DatabaseQueries {

@Inject 
private ComboPooledDataSource comboPooledDataSource;

public List<Records> getData() {
    Connection connection = comboPooledDataSource.getConnection();
    // ... create sql query and execute 
}

そして使用法:

@Component
public class AnotherBean{

    @Inject 
    private DatabaseQueries queries;

    public void doSomething {
        List<Records> data = queries.getData();
    }
}
于 2013-08-20T20:19:11.543 に答える
1

これは、Spring エラーというよりも Java エラーです。

メソッド getData() を非静的として宣言する必要があります。

于 2013-08-20T20:13:43.613 に答える