首页 > 解决方案 > 具有@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;
 }

标签: javasqlspring-bootjooq

解决方案


当然,您可以继续注入为每个查询创建 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);
    }
}

推荐阅读