gpt4 book ai didi

java - 学习Spring/Java : How To Inject Spring Bean

转载 作者:行者123 更新时间:2023-12-01 18:44:36 25 4
gpt4 key购买 nike

我正在同时学习Spring和Java。我正在研究我的应用程序上下文。这是我的一颗 bean :

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?

预先感谢,请记住,我正在学习!

最佳答案

您的方法 getData() 是静态的。当使用 Spring 或一般使用依赖注入(inject)时,您使用的静态方法比以前少得多。使其成为非静态的。当您需要使用 DatabaseQueries 时,您可以再次注入(inject)它。

@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();
}
}

关于java - 学习Spring/Java : How To Inject Spring Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18344138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com