@Value返回null

时间:2019-07-15 16:54:29

标签: java spring properties properties-file

我正在尝试从属性文件中获取值,下面是我尝试注入URL的尝试。不知道我是否正确地做到了。

我已经在属性文件中为URL设置了一些东西,并且我可以肯定我的注入方法是错误的,但是我是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;
    }

2 个答案:

答案 0 :(得分:0)

applicationContext.xml 中,您必须添加要从类路径读取的属性文件:

<context:property-placeholder location="classpath:something.properties, classpath:demo.properties" />

如果要添加多个属性文件,只需用逗号分隔即可添加

像这样更新您的课程:

public class DatabaseHelperClass {

  @Value("${databaseURL}")
  static String 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;
}

答案 1 :(得分:0)

如果我使用的是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();
  }
}