java - @Value 返回 null

标签 java spring properties properties-file

我正在尝试从属性文件中获取值,下面是我尝试注入(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/

相关文章:

java - 使用 spring.Headache 使用 hibernate genericdao 模式测试 dao

python - 在 Python 中具有依赖性的惰性数据流(类似电子表格)属性

java - 如何将属性文件中的空值添加到 map

java - 如何用另一个 java.util.Properties 中的所有对覆盖 java.util.Properties 中的某些对?

java - 用于添加图像的 Wicket 拖放功能

java - 如何解决 wsdl2java 上 ObjectFactory 中的冲突?

Java服务器android客户端通过不同网络进行通信

java - 从服务异常中检索 Spring Integration 中的消息

java - 构造函数未按预期打印

spring - 一个组件需要一个名为 '' 的 bean,但是找不到