【发布时间】:2021-08-03 18:59:25
【问题描述】:
我目前正在尝试从我的 application.properties 文件中连接一个数据库,以在不同的类中获得 JDBC 连接。我使用了以下方法。
@Component
public class databaseConn {
public static int counter=0;
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
//Retrieves Everything from the database and sends it to the front end
public ArrayList<Alert> datacon() throws ClassNotFoundException, SQLException {
ArrayList<Alert> giveBack = new ArrayList<Alert>();
Statement stmt = null;
Connection conn=null;
System.out.println(url);
System.out.println(username);
System.out.println(password);
try {
conn = DriverManager.getConnection(url, username, password);
}
catch (Exception e){
System.out.println("Couldn't Connect");
}
由于某种原因,当我打印这些值时,它们显示为 Null 并且无法连接。我做错了什么?
编辑:这是 application.properties 文件。我修改了每个字段的值,但可以看到其他所有内容
spring.application.name=sampleApp
spring.datasource.url=xxxx
spring.datasource.username=username
spring.datasource.password=password
spring.http.encoding.enabled=false
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
【问题讨论】:
-
你能显示 application.properties 文件吗?
-
@ErkanErkişi 刚刚添加
-
这些可能为空的原因有很多。另外,请记住,如果您使用的是 spring.datasource,则可以直接 Autowire 数据源。
-
是的,我同意@lane.maxwell。我认为您的课程在我看来没有被视为一个组件。
标签: spring spring-boot jdbc null