I am a beginner with Spring
and I am working on a spring-boot
project with Jooq
.
I created an application properties which loads the database access settings, it's working, but I need a connection class that returns a connection object for me to use when needed.
It would be better if this class had a static
getConnection
method. I wrote the class as @Component
and I put my
@Value
but all these attributes are null
when I try to use them.
Is there another way to do this? Thank you so much.
@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());
}
}
}
that way I would use it in other classes
try (Connection con = ConnectionFactory.getConnection()) {
DSLContext ctx = DSL.using(con, SQLDialect.MYSQL);
int count = ctx.selectCount()
.from(ALUNO)
.fetchOne(0, int.class);
return count;
}