我正在尝试从属性文件中获取值,下面是我尝试注入(inject) URL。不确定我这样做是否正确。
我已经在属性文件中为 URL 设置了一些内容,并且我很确定我的注入(inject)方法是错误的,但我是一个 java 新手,所以我无法真正找出解决方案。
public class DatabaseHelperClass {
static String URL;
@Value("${databaseURL}")
public void propertiesSetter(String URL) {
DatabaseHelperClass.URL = URL;
}
public static Connection getOracleConnection() throws SQLException{
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class");
System.exit(1);
}
catch(IllegalAccessException ex) {
System.out.println("Error: access problem while loading");
System.exit(2);
}
catch(InstantiationException ex) {
System.out.println("Error: unable to instantiate driver");
System.exit(3);
}
System.out.print(URL);
Connection connection = null;
System.out.println();
try {
connection = DriverManager.getConnection(URL);
System.out.print(connection);
}
catch(SQLException e) {
System.out.println(e.getMessage());
}
return connection;
}
最佳答案
如果你使用 Spring 框架,我假设,简单地编写 @Value 注释是行不通的。您必须编写一个有助于识别属性文件名的调用。我在下面提供了一个例子。
@Configuration
@PropertySources({
@PropertySource("file:config/credentials-config.properties"),
@PropertySource("file:config/app-config.properties")
})
public class ConfigReader {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
关于java - @Value 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57044151/