0

I am learning Spring and Java at the same time. I am working on my application context. Here is one of my beans:

package com.example.app.context;

@Configuration
public class ApplicationContextConfiguration {

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

Now I want to use this 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 
} 

But I get this error at compile time:

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

How do I access this bean?

Thanks in advance, and please remember, I'm learning!

David Williams
  • 8,388
  • 23
  • 83
  • 171

2 Answers2

3

Your method getData() ist static. when working with Spring or in generally with Dependency Injection you use static methods much less than you might used to be. Make it non-static. When ever you need to to use your DatabaseQueries, you inject it again.

@Component
public class DatabaseQueries {

@Inject 
private ComboPooledDataSource comboPooledDataSource;

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

And the usage:

@Component
public class AnotherBean{

    @Inject 
    private DatabaseQueries queries;

    public void doSomething {
        List<Records> data = queries.getData();
    }
}
fischermatte
  • 3,327
  • 4
  • 42
  • 52
1

This is more of a Java error than a Spring one.

You need to declare the method getData() as not static.

UpAllNight
  • 1,312
  • 3
  • 18
  • 30