2017-11-10 1 views
1

아래의 방법을 사용하여 속성 파일에서 모든 속성을 가져 오려고합니다.@configuration 주석이 달린 클래스를 사용하여 속성에 액세스

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 

아래 리소스를 사용해 보았습니다. 그러나, 나는 꽤 주입이 발생하기 전에 호출되는 응용 프로그램

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

+0

주입/자동 배선은 언제 발생한다고 생각하십니까? 앞이나 뒤에'filePath'의 할당이 실행됩니까? – luk2302

+0

나는 주입이 주석에 근거한 과제 전에 일어난다 고 생각합니다. 내 이해가 맞습니까? – dataEnthusiast

+0

아닙니다. 불가능합니다. 객체에 어떤 일이 생기기 전에 인스턴스를 생성해야합니다. 인스턴스가 생성되면 변수'filePath'가 정의되고 할당됩니다. 그 이후에야 필드 주입이 일어날 수 있습니다. 내가 뭘 하려는지 이해가 안되는데 왜 Configuration 클래스에 Bean이 포함되어 있지 않은지, 왜 Configuration 클래스 자체가 Component 인지요? – luk2302

답변

0

개체의 생성자를 통해 속성에 액세스 할 수 @Bean을 사용하는 방법을 이해하고 있지 않다.

생성자를 호출하면 filePath과 같은 변수가 초기화되지만이 시점에서 env은 아직 삽입되지 않으며 null입니다.

는 모든 주사가 ​​이미 완료되었음을 보장 인스턴스 메서드를 호출 할 때 당신은 다음과 같은 몇 가지 방법을 가지고 고려할 수

이 : 부동산 주입

String getFilePath(){ 

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

는 단순히 걸릴 장점 :

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

이 값을 포함하는 파일은 @PropertySource을 사용하여 등록됩니다.

+0

인스턴스 변수 ** public **을 만들지 마십시오. –

+2

내가 말할 것 인 생각없이 붙여 넣기하지 마라. .. updated –

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 Profiles YAML Properties example

희망이 도움을!

관련 문제