gpt4 book ai didi

java - 从属性源读取数据库属性不起作用

转载 作者:行者123 更新时间:2023-11-29 06:28:34 24 4
gpt4 key购买 nike

我想从 application.property 文件中读取数据库属性值,但无法读取。

我尝试从自定义属性文件中读取属性,但没有成功。我不想对属性进行硬编码,因为它在不同的服务器中会有所不同。

@Configuration
@PropertySource("application.properties")
public class DatabaseUtils {

@Value("${mysql.drive}")
private static String MY_SQL_DRIVER;

@Value("${mysql.url}")
private static String MY_SQL_URL;

@Value("${mysql.username}")
private static String DATABASE_USERNAME;

@Value("${mysql.password}")
private static String DATABASE_PASSWORD;

public DatabaseUtils () {

}

@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}

public static ResultSet executeDBQuery(String query) {
try {

Class.forName(MY_SQL_DRIVER);
Connection connection = DriverManager.getConnection(MY_SQL_URL, DATABASE_USERNAME, DATABASE_PASSWORD);

Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
return resultSet;
} catch (Exception e) {
e.printStackTrace();
return null;
}

}
}


(properties file)
# database
databaseDriver=com.mysql.jdbc.Driver
databaseUrl=jdbc:mysql://localhost:3306/school
databaseUsername=root
databasePassword=root

I am new to spring-boot so getting a little confused as to why its not working, read a lot of online sources and tried them but didnt work, not sure what I am missing. Any help will be appreciated.

最佳答案

您的属性文件中的属性与您在 @Value.for 中给出的属性不同,例如。您的属性键是databaseDriver,但您在代码中提供了mysql.drive。

 @Value("${mysql.drive}")
private static String MY_SQL_DRIVER;

但应该是

@Value("${databaseDriver}")
private static String MY_SQL_DRIVER;

关于java - 从属性源读取数据库属性不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58025318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com