使用@configuration注释的类访问属性

时间:2017-11-10 08:46:59

标签: java spring-boot

我正在尝试使用以下方法从属性文件中获取所有属性。

我遇到一个异常,即FilterConfigurations类无法实例化。从属性文件访问属性的最佳方法是什么。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
@Configuration
@PropertySource("classpath:configuration.properties")
public class FilterConfigurations {

    @Autowired
    private Environment env;

    public  String filePath = env.getProperty("file.path");

}



import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.cisco.sso.daas.models.User;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class FileOperations<T> implements Operations<T> {

    private ObjectMapper objectMapper;
    //private FilterConfigurations fc;
    private File file;
    //private String filePath = fc.filePath;
    // this is going to come from the property file.
    private String filePath = "C:\\Users\\phyadavi\\SYSLOG-NG\\platform\\syslogng\\FilteringService\\src\\main\\resources\\seed.txt";

    // private T targetClass;

    public FileOperations() {
        this.objectMapper = new ObjectMapper();
        this.file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.getMessage();
            }
        }
    }

    private void saveImpl(Object serializableObject) throws IOException {
        String jsonData = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(serializableObject);
        BufferedWriter br = new BufferedWriter(new FileWriter(file));
        br.write(jsonData);
        br.close();
    }

    @Override
    public void save(List<T> serializableObjects) throws IOException {
        saveImpl(serializableObjects);
    }

    @Override
    public void save(T serializableObject) throws IOException {
        saveImpl(serializableObject);
    }

    @Override
    public List<T> get() throws IOException {
        // JavaType type =
        // objectMapper.getTypeFactory().constructCollectionType(ArrayList.class,
        // targetClass.getClass());
        // List<T> list = objectMapper.readValue(file, type);
        List<T> list = objectMapper.readValue(file, new TypeReference<List<User>>() {
        });
        if (list == null) {
            List<T> list1 = new ArrayList<T>();
            return list1;
        }
        return list;
    }

}

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-11-10 13:19:40.510 ERROR 7324 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'filterConfigurations' defined in file [C:\Users\phyadavi\SYSLOG-NG\platform\syslogng\FilteringService\target\classes\com\cisco\sso\daas\application\FilterConfigurations.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.cisco.sso.daas.application.FilterConfigurations$$EnhancerBySpringCGLIB$$58eb5e77]: Constructor threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1155) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at com.cisco.sso.daas.application.ConfigurationServiceApplication.main(ConfigurationServiceApplication.java:14) [classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.cisco.sso.daas.application.FilterConfigurations$$EnhancerBySpringCGLIB$$58eb5e77]: Constructor threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1147) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    ... 17 common frames omitted
Caused by: java.lang.NullPointerException: null
    at com.cisco.sso.daas.application.FilterConfigurations.<init>(FilterConfigurations.java:17) ~[classes/:na]
    at com.cisco.sso.daas.application.FilterConfigurations$$EnhancerBySpringCGLIB$$58eb5e77.<init>(<generated>) ~[classes/:na]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_144]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.8.0_144]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.8.0_144]
    at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[na:1.8.0_144]
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    ... 19 common frames omitted

我也尝试使用以下资源。但是,我完全不了解如何使用@Bean访问应用程序中的属性

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

3 个答案:

答案 0 :(得分:1)

您可以参考两种方式:

a)使用属性注入,例如:

@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.javabycode.springmvc.configuration" })
@PropertySource(value = { "classpath:jdbc.properties" })
public class MyHibernateConfig {

    @Autowired
    private Environment environment;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }
}

post

中找到此信息

b)使用Spring Boot Profile,例如:

这里很难给你提供示例代码。查看帖子Spring Boot Profiles YAML Properties example

希望这有帮助!

答案 1 :(得分:0)

在注入发生之前调用对象的构造函数。

调用构造函数会初始化您的变量,例如filePath,但此时env仍未注入且null

您可以考虑使用以下方法,在调用实例方法时,您可以保证所有注射都已完成:

String getFilePath(){

    return env.getProperty("file.path");
}

答案 2 :(得分:0)

我只是利用财产注入:

@Value("${file.path}")
private String filePath; 

使用@PropertySource注册包含该值的文件。