【发布时间】:2018-11-03 16:44:50
【问题描述】:
我是Spring 的初学者,我正在使用Jooq 进行spring-boot 项目。
我创建了一个应用程序属性 加载数据库访问设置, 它正在工作,但我需要一个连接类,它返回一个连接对象供我在需要时使用。
如果这个类有一个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;
}
【问题讨论】:
标签: java sql spring-boot jooq