복붙노트

[SPRING] Spring 부트 application.properties 값이 채워지지 않습니다.

SPRING

Spring 부트 application.properties 값이 채워지지 않습니다.

일부 외형화된 구성으로 작업하려고하는 매우 간단한 스프링 부트 응용 프로그램이 있습니다. 나는 스프링 부트 문서의 정보를 따르려고했지만로드 블록을 치고있다.

아래의 애플리케이션을 실행할 때 application.properties 파일의 외부 구성이 bean 내의 변수에 채워지지 않습니다. 나는 어리석은 짓을하고 있다고 확신한다. 어떤 제안이라도 고맙다.

MyBean.java (/ src / main / java / foo / bar /에 있습니다)

package foo.bar;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
public class MyBean {

    @Value("${some.prop}")
    private String prop;

    public MyBean() {
        System.out.println("================== " + prop + "================== ");
    }
}

Application.java (/ src / main / java / foo /에 있습니다)

package foo;

import foo.bar.MyBean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {

    @Autowired
    private MyBean myBean;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

application.properties (/ src / main / resources /에 있습니다)

some.prop=aabbcc

Spring Boot app 실행시 로그 출력 :

grb-macbook-pro:properties-test-app grahamrb$ java -jar ./build/libs/properties-test-app-0.1.0.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.1.5.RELEASE)

2014-09-10 21:28:42.149  INFO 16554 --- [           main] foo.Application                          : Starting Application on grb-macbook-pro.local with PID 16554 (/Users/grahamrb/Dropbox/dev-projects/spring-apps/properties-test-app/build/libs/properties-test-app-0.1.0.jar started by grahamrb in /Users/grahamrb/Dropbox/dev-projects/spring-apps/properties-test-app)
2014-09-10 21:28:42.196  INFO 16554 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@67e38ec8: startup date [Wed Sep 10 21:28:42 EST 2014]; root of context hierarchy
2014-09-10 21:28:42.828  INFO 16554 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2014-09-10 21:28:43.592  INFO 16554 --- [           main] .t.TomcatEmbeddedServletContainerFactory : Server initialized with port: 8080
2014-09-10 21:28:43.784  INFO 16554 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2014-09-10 21:28:43.785  INFO 16554 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.54
2014-09-10 21:28:43.889  INFO 16554 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2014-09-10 21:28:43.889  INFO 16554 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1695 ms
2014-09-10 21:28:44.391  INFO 16554 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2014-09-10 21:28:44.393  INFO 16554 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
================== null==================
2014-09-10 21:28:44.606  INFO 16554 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-09-10 21:28:44.679  INFO 16554 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2014-09-10 21:28:44.679  INFO 16554 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[text/html],custom=[]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
2014-09-10 21:28:44.716  INFO 16554 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-09-10 21:28:44.716  INFO 16554 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-09-10 21:28:44.902  INFO 16554 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2014-09-10 21:28:44.963  INFO 16554 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080/http
2014-09-10 21:28:44.965  INFO 16554 --- [           main] foo.Application                          : Started Application in 3.316 seconds (JVM running for 3.822)
^C2014-09-10 21:28:54.223  INFO 16554 --- [       Thread-2] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@67e38ec8: startup date [Wed Sep 10 21:28:42 EST 2014]; root of context hierarchy
2014-09-10 21:28:54.225  INFO 16554 --- [       Thread-2] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

해결법

  1. ==============================

    1.속성의 주입을 수행하는 방법은 작동하지 않습니다. 왜냐하면 주입은 생성자가 호출 된 후에 수행되기 때문입니다.

    속성의 주입을 수행하는 방법은 작동하지 않습니다. 왜냐하면 주입은 생성자가 호출 된 후에 수행되기 때문입니다.

    다음 중 하나를 수행해야합니다.

    더 나은 솔루션

    @Component
    public class MyBean {
    
        private final String prop;
    
        @Autowired
        public MyBean(@Value("${some.prop}") String prop) {
            this.prop = prop;
            System.out.println("================== " + prop + "================== ");
        }
    }
    

    작동하지만 덜 테스트 가능하고 약간 읽기 어려운 솔루션

    @Component
    public class MyBean {
    
        @Value("${some.prop}")
        private String prop;
    
        public MyBean() {
    
        }
    
        @PostConstruct
        public void init() {
            System.out.println("================== " + prop + "================== ");
        }
    }
    

    또한 Spring Boot에만 국한되지 않고 모든 Spring 애플리케이션에 적용됩니다.

  2. ==============================

    2.사용자 "geoand"는 여기에 이유를 지적하고 해결책을 제시합니다. 그러나 더 나은 방법은 구성을 별도의 클래스로 캡슐화하는 것입니다. 예를 들어 SystemContiguration java 클래스를 호출 한 다음이 클래스를 서비스에 추가하여 해당 필드를 사용하려고합니다.

    사용자 "geoand"는 여기에 이유를 지적하고 해결책을 제시합니다. 그러나 더 나은 방법은 구성을 별도의 클래스로 캡슐화하는 것입니다. 예를 들어 SystemContiguration java 클래스를 호출 한 다음이 클래스를 서비스에 추가하여 해당 필드를 사용하려고합니다.

    구성 값을 서비스로 직접 읽는 현재 방식 (@grahamrb)은 오류가 발생하기 쉽고 구성 설정 이름이 변경되면 리팩토링 두통을 일으킬 수 있습니다.

  3. ==============================

    3.사실, 아래 나를 위해 잘 작동합니다.

    사실, 아래 나를 위해 잘 작동합니다.

    @Component
    public class MyBean {
    
       public static String prop;
    
       @Value("${some.prop}")
       public void setProp(String prop) {
          this.prop= prop;
       }
    
       public MyBean() {
    
       }
    
       @PostConstruct
       public void init() {
          System.out.println("================== " + prop + "================== ");
       }
    

    }

    이제 어디서나 원하는대로 호출합니다.

    MyBean.prop

    그것은 값을 반환합니다.

  4. from https://stackoverflow.com/questions/25764459/spring-boot-application-properties-value-not-populating by cc-by-sa and MIT license