简体   繁体   English

属性在基于Spring Boot的Java应用程序中不起作用

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

i have spring boot based java app. 我有基于Spring Boot的Java应用程序。 i am using java.util.properties to read the properties from application.properties file present in src/main/resources (default path). 我正在使用java.util.properties从src / main / resources(默认路径)中存在的application.properties文件读取属性。 i have just defined the getters and setters to read the props. 我刚刚定义了用于读取道具的吸气剂和吸气剂。 following is the code : 以下是代码:

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;
    }

}

now, in another class, just creating the object of this class and trying to call the getHost() method to get the host ip address. 现在,在另一个类中,只需创建该类的对象并尝试调用getHost()方法即可获取主机ip地址。

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

getting following exception : 得到以下异常:

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

without using properties class, if i just hard code the IP address, it absolutely works fine. 不使用属性类,如果我只是硬编码IP地址,那绝对可以正常工作。 dont know what the issue in the code so the property reader is not working. 不知道代码中的问题,因此属性读取器无法正常工作。

following the application.properties content: 遵循application.properties内容:

spring.mysql.host=35.154.83.162

Update :::: 更新::::

here is the code updated : 这是更新的代码:

@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");

}
}

getting NPE exception : 获取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

In spring boot you don't need to read properties manually (specially application.properties ). 在春季启动中,您无需手动读取属性(特别是application.properties )。
application.properties (.yml|.yaml) is by default loaded into spring Environemnt class. 默认情况下,application.properties(.yml | .yaml)被加载到spring Environemnt类中。

@Component
public class PropertyReader {

    @Autowired
    private Environment env;

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

To use it, just autowire PropertyReader and call getHost() method. 要使用它,只需自动装配PropertyReader并调用getHost()方法。
Even you don't need to write this class, you can directly use Environment class as well. 即使您不需要编写此类,也可以直接使用Environment类。

EDIT (After Question Update) 编辑(问题更新后)

Solution 1 (Using Environment) 解决方案1(使用环境)

Move your constructor code to init method, at that point env is not initialized. 将构造函数代码移到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 
    }
}

Solution 2 (Using @Value) 解决方案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