java - 具有@value 属性的连接类
问题描述
我是初学者,Spring
我正在spring-boot
使用Jooq
.
我创建了一个加载数据库访问设置的应用程序属性,它正在工作,但我需要一个连接类,它返回一个连接对象供我在需要时使用。
如果这个类有一个static
getConnection
方法会更好。我写了这个类@Component
,我把我的
@Value
但所有这些属性都是null
当我尝试使用它们时。
还有另一种方法可以做到这一点吗?太感谢了。
@Component
public class ConnectionFactory {
@Value("${bws.codigo.escola}")
static private String codigoEscola;
@Value("${bws.driver.connection}")
static private String driver;
@Value("${bws.database.name}")
static private String nameDb;
@Value("${bws.database.user}")
static private String user;
@Value("${bws.database.password}")
static private String password;
@Value("${bws.database.server}")
static private String server;
@Value("${bws.string.connection}")
static private String firstUrlPart;
@Value("${bws.string.connectionLast}")
static private String lastPartUrl;
@Value("${bws.database.port}")
static private String port;
static String strConnection = firstUrlPart+server+":"+port+"/"+nameDb+lastPartUrl;
public static Connection getConnection() throws SQLException {
try {
Class.forName(driver);
return DriverManager.getConnection(strConnection,
user,password);
} catch (ClassNotFoundException e) {
throw new SQLException(e.getMessage());
}
}
}
这样我会在其他课程中使用它
try (Connection con = ConnectionFactory.getConnection()) {
DSLContext ctx = DSL.using(con, SQLDialect.MYSQL);
int count = ctx.selectCount()
.from(ALUNO)
.fetchOne(0, int.class);
return count;
}
解决方案
当然,您可以继续注入为每个查询创建 JDBC 连接所需的所有值。或者,更好的是,您注入一个预先配置的DSLContext
单例实例,该实例通过 a 包装 JDBC 连接DataSource
(理想情况下由连接池实现)。
Spring Boot 手册说明了如何做到这一点: https ://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html#boot-features-jooq
一个更完整的例子可以在这里看到: https ://github.com/jOOQ/jOOQ/tree/master/jOOQ-examples/jOOQ-spring-boot-example
目标是:
class SomeClass {
@Autowired
DSLContext ctx;
public int countAluno() {
return ctx.selectCount()
.from(ALUNO)
.fetchOne(0, int.class);
}
}
推荐阅读
- r - 如何使用闪亮实时修改文件?
- java - Android Studio 导入 com.google.android.vending.expansion.zipfile.ZipResourceFile;不存在
- bash - 基于一列的两个大文件的连接命令给出空输出
- node.js - 不和谐嵌入错误类型错误:无法读取未定义的属性“客户端”
- node.js - Mongodb 与 mongoose 和 pymongo
- android - Seekbar 不与 exoplayer android 一起移动
- google-sheets - 谷歌工作表数组公式 sumif 只有第一个实例
- c++ - C++20
嵌套名称说明符中使用的不完整类型 - python - 通过增加mongodb id来添加数据
- c# - DDD - 如何强制执行不变量但特定于客户要求?