【问题标题】:Connection class with @value properties [duplicate]具有@value 属性的连接类 [重复]
【发布时间】: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


    【解决方案1】:

    当然,您可以继续注入所有需要的值,以便为您的每个查询临时创建 JDBC 连接。或者,更好的是,您注入一个预先配置的 DSLContext 单例实例,该实例通过 DataSource 包装 JDBC 连接(理想情况下由连接池实现)。

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

    【讨论】:

      猜你喜欢
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      • 2013-12-15
      • 1970-01-01
      • 2015-08-13
      • 2011-01-03
      • 2018-07-10
      相关资源
      最近更新 更多