簡體   English   中英

屬性在基於Spring Boot的Java應用程序中不起作用

[英]Properties are not working in spring-boot based java application

我有基於Spring Boot的Java應用程序。 我正在使用java.util.properties從src / main / resources(默認路徑)中存在的application.properties文件讀取屬性。 我剛剛定義了用於讀取道具的吸氣劑和吸氣劑。 以下是代碼:

public class PropertyReader {

    String host;

    public String getHost() {

        Properties properties = new Properties();
        try {
            File file = ResourceUtils.getFile("classpath:application.properties");
            InputStream in = new FileInputStream(file);
            properties.load(in);
        } catch (IOException e) {

        }
        return host = properties.getProperty("spring.mysql.host");
    }

    public void setHost(String host) {
        this.host = host;
    }

}

現在,在另一個類中,只需創建該類的對象並嘗試調用getHost()方法即可獲取主機ip地址。

PropertyReader pr = new PropertyReader();
String host = pr.getHost();
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:mysql://" + host + "/ci");

得到以下異常:

Caused by: java.net.UnknownHostException: null
        at java.net.InetAddress.getAllByName0(InetAddress.java:1280) ~[na:1.8.0_151]
        at java.net.InetAddress.getAllByName(InetAddress.java:1192) ~[na:1.8.0_151]
        at java.net.InetAddress.getAllByName(InetAddress.java:1126) ~[na:1.8.0_151]
        at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:188) ~[mysql-connector-java-5.1.45.jar!/:5.1.45]
        at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:300) ~[mysql-connector-java-5.1.45.jar!/:5.1.45]
        ... 44 common frames omitted

不使用屬性類,如果我只是硬編碼IP地址,那絕對可以正常工作。 不知道代碼中的問題,因此屬性讀取器無法正常工作。

遵循application.properties內容:

spring.mysql.host=35.154.83.162

更新::::

這是更新的代碼:

@Component
@Configuration
public class UnitDBHelper {
@Autowired
    private Environment env;

public UnitDBHelper() {

        String host = env.getProperty("spring.mysql.host");     
        PoolProperties p = new PoolProperties();
        InputStream input = null;
        p.setUrl("jdbc:mysql://" + host + "/ci");

}
}

獲取NPE異常:

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2018-05-30 15:42:29.532 ERROR 9870 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'unitDBHelper' defined in URL [jar:file:/tmp/unitdbamqpservice-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/com/infy/ci/unitdbamqpservice/UnitDBHelper.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.infy.ci.unitdbamqpservice.UnitDBHelper$$EnhancerBySpringCGLIB$$24a2dca6]: Constructor threw exception; nested exception is java.lang.NullPointerException

Caused by: java.lang.NullPointerException: null
        at com.infy.ci.unitdbamqpservice.UnitDBHelper.<init>(UnitDBHelper.java:39) ~[classes!/:0.0.1-SNAPSHOT]
        at com.infy.ci.unitdbamqpservice.UnitDBHelper$$EnhancerBySpringCGLIB$$24a2dca6.<init>(<generated>) ~[classes!/:0.0.1-SNAPSHOT]
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_151]
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_151]
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_151]
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_151]
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142) ~[spring-beans-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
        ... 27 common frames omitted

在春季啟動中,您無需手動讀取屬性(特別是application.properties )。
默認情況下,application.properties(.yml | .yaml)被加載到spring Environemnt類中。

@Component
public class PropertyReader {

    @Autowired
    private Environment env;

    public String getHost() {
        return env.getProperty("spring.mysql.host");
    }
}

要使用它,只需自動裝配PropertyReader並調用getHost()方法。
即使您不需要編寫此類,也可以直接使用Environment類。

編輯(問題更新后)

解決方案1(使用環境)

將構造函數代碼移到init方法,此時env尚未初始化。

public class UnitDBHelper implements InitializingBean {

    // your autowires

    @Override
    public void afterPropertiesSet() throws Exception {
        // your constructor code,
        // this will be called after injecting all beans
        // use `env` here 
    }
}

解決方案2(使用@Value)

@Component
public class UnitDBHelper {

    @Value("${spring.mysql.host}")
    private String host;

    // you can still not use host in constructor
    // as it will be uninitialized 

    //  rest of code
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM