Spring Bootapplication.propertiesの値が入力されていません


97

非常にシンプルなSpringBootアプリがあり、外部化された構成で動作させようとしています。スプリングブーツのドキュメントの情報に従おうとしましたが、障害にぶつかっています。

以下のアプリを実行すると、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

SpringBootアプリの実行時のログ出力

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

4
そして@Value、Beanを構築する前にどのように交換する必要がありますか?値が設定されているかどうかを「検出」する方法が間違っています。その時点では、@Valueオブジェクトの構築後に処理されるため、常にnullになります。
M. Deinum 2014

回答:


165

コンストラクターが呼び出された後に注入が行われるため、プロパティの注入を実行する方法は機能しません。

次のいずれかを行う必要があります。

より良い解決策

@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アプリケーションに適用されることに注意してください。


私はそれを動作させるためにコンストラクタに@Autowired注釈を追加する必要がありました
セバスチャン・Tromp

1
ヒントをありがとう。これは、@ Valueアノテーションについて説明しているSpringのドキュメントにあるはずですが、それらの人はドキュメントへのフィードバックに興味がないようです:(
Alex Worden 2015

1
私にいくつかのfrsutrationを保存しました。ありがとう!
ロバートモスカル2016年

1
@geoand 10を超える値がある場合、10個すべてを入力したとおりに入力する必要がありますか?または、よりクリーンな方法はありますか
Jesse

1
@ジャッキー確かに、よりクリーンな方法があります!チェックアウト@ConfigurationProperties@EnableConfigurationProperties注釈
geoand 2016

5

ユーザー「geoand」は、ここで理由を指摘し、解決策を提供するのに正しいです。ただし、より良いアプローチは、構成を別のクラス、たとえばSystemContiguration javaクラスにカプセル化してから、これらのフィールドを使用するサービスにこのクラスを挿入することです。

構成値をサービスに直接読み取る現在の方法(@grahamrb)はエラーが発生しやすく、構成設定名が変更された場合にリファクタリングの問題が発生します。


そのプロパティに別のクラスがあるとしたら、どうして頭痛の種が減らないでしょうか。あなたはまだリファクタリング時に覚えておく必要がある文字列があります
dot_Sp0T

4
N番号ではなく、「覚えておく」必要のある場所は1つだけです。SystemContigurationに存在するスカラー値は、強い型付けを提供します。また、構成からの値に基づいて~~~「フォーク」を持つビジネスロジックがある場合は~~~ .....値を必要とするクラス/ businessLogicに何かを注入することをお勧めします。別名、SystemContigurationをモックしてから、@ Valueをあらゆる場所で機能させようとする方がはるかに簡単です。
granadaCoder 2018

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

値を返します。


2

この回答は、あなたのケースに当てはまる場合と当てはまらない場合があります...同様の症状があり、コードを何度も再確認したところ、すべて問題ないように見えましたが、@Value設定はまだ有効ではありませんでした。そして、File > Invalidate Cache / Restart私のIntelliJ(私のIDE)で行った後、問題はなくなりました...

これは試すのがとても簡単なので、一見の価値があるかもしれません


1

環境クラスを使用して、アプリケーションを取得できます。プロパティ値

@ Autowired、

private Environment env;

およびを使用してアクセスする

String password =env.getProperty(your property key);

0

次の手順を実行します。1:-以下のような構成クラスを作成します。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;

@Configuration
public class YourConfiguration{

    // passing the key which you set in application.properties
    @Value("${some.pro}")
    private String somePro;

   // getting the value from that key which you set in application.properties
    @Bean
    public String getsomePro() {
        return somePro;
    }
}

2:-構成クラスがある場合は、必要な構成から変数を挿入します。

@Component
public class YourService {

    @Autowired
    private String getsomePro;

    // now you have a value in getsomePro variable automatically.
}

0

複数の異なるapplication.propertiesファイルを含む大規模なマルチモジュールプロジェクトで作業している場合は、プロジェクトのプロパティファイルに値を追加してみてください。

親プロジェクトがどれであるかわからない場合は、プロジェクトのpom.xmlファイルで<parent>タグを確認してください。

これで問題は解決しました。


0

Environmentクラスを使用してデータを取得できます。

@Autowired
private Environment env;
String prop= env.getProperty('some.prop');
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.