文字列値のプレースホルダーを解決できませんでした


88

.propertiesファイルのプロパティを使用しようとしていますが、機能しないようです。

これが私のコードです:

@Service("ServiceFTP")
@Transactional
public class ServiceFTPImpl implements ServiceFTP {

@Value("${project.ftp.adresse}")
private String adresse;

@Value("${project.ftp.login}")
private String compte;

@Value("${project.ftp.password}")
private String motDePasse;

@Value("${project.ftp.root}")
private String ROOT;

[...]

}

このクラスは、@Valueアノテーションを使用してプロパティを取得します。また、Spring Serviceとして宣言されており、私のinfraContext.xmlファイルにリンクされています。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

<context:property-placeholder location="classpath:context-core.properties"/>

[...]

</beans>

を使用してcontext:property-placeholder、このファイルを自分のcontext-core.propertiesファイルにリンクします。

project.ftp.adresse = localhost
project.ftp.login = anonymous
project.ftp.password =
project.ftp.root = /anonymous/

これは理にかなっていますよね?

しかし、プロジェクトを起動しようとすると、Tomcatは次の例外をスローします。

    ERROR [context.ContextLoader.initWebApplicationContext()] Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ServiceFTP': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String project.sins.service.impl.ServiceFTPImpl.adresse; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'project.ftp.adresse' in string value "${project.ftp.adresse}"
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:472)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:388)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:293)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4887)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5381)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1636)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String project.sins.service.impl.ServiceFTPImpl.adresse; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'project.ftp.adresse' in string value "${project.ftp.adresse}"
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:513)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:92)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
    ... 27 more
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'project.ftp.adresse' in string value "${project.ftp.adresse}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:173)
    at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:125)
    at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:151)
    at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:142)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:169)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:748)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:740)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:485)
    ... 29 more

または、要するに: java.lang.IllegalArgumentException: Could not resolve placeholder 'project.ftp.adresse' in string value "${project.ftp.adresse}"

編集:

これが私のweb.xmlです:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="sins" version="2.5">

    <display-name>Project</display-name>

    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <context-param>
        <param-name>log4jExposeWebAppRoot</param-name>
        <param-value>false</param-value>
    </context-param>

    <filter>
        <filter-name>ExpiresFilter</filter-name>
        <filter-class>org.apache.catalina.filters.ExpiresFilter</filter-class>
        <init-param>
            <param-name>ExpiresByType text/html</param-name>
            <param-value>now plus 0 seconds</param-value>
        </init-param>
        <init-param>
            <param-name>ExpiresByType application/json</param-name>
            <param-value>now plus 0 seconds</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>ExpiresFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
    </filter-mapping>

    <filter>
        <filter-name>EncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>EncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
        <filter-class>
            org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
        </filter-class>
    </filter>

    <filter-mapping>
        <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
    </listener>

    <context-param>
        <param-name>
            org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG
        </param-name>
        <param-value>
            /WEB-INF/tiles/user.xml
        </param-value>
    </context-param>

    <resource-ref>
        <res-ref-name>jdbc/si_nsg</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>

    <session-config>
        <session-timeout>60</session-timeout>
    </session-config>

</web-app>

私のinfraContext.xmlは、applicationContext.xmlという名前の別の.xmlファイルにインポートされます。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd">

    <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="environment">
            <bean class="org.springframework.web.context.support.StandardServletEnvironment"/>
        </property>
    </bean>

    <import resource="classpath:securityContext.xml"/>

    [...]
    <import resource="classpath:project/sins/persistenceContext.xml"/>

    <import resource="classpath:project/sins/infraContext.xml"/>

</beans>

私は明らかに何かが足りないのですが、何がわからないのです。

詳細が必要な場合はお知らせください。ここでの最初の質問ですので、できるだけ早く回答させていただきます:)。


1
どこinfraContext.xmlにロードされていますか?スタックトレースから判断すると、によってロードされる構成には含まれていませんContextLoaderListener。web.xmlを投稿してください。
M. Deinum 2013年

2
問題は、PropertySourcesPlaceholderConfigurer明示的に定義されたインスタンスと名前空間が原因のインスタンスが複数あることです。あなたの中の人はapplicationContext.xml何もしておらず、何も追加していません。それを除く。
M. Deinum 2013年

回答:


74

構成には2つのPropertySourcesPlaceholderConfigurerインスタンスがあります。

applicationContext.xml

<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="environment">
        <bean class="org.springframework.web.context.support.StandardServletEnvironment"/>
    </property>
</bean>

infraContext.xml

<context:property-placeholder location="classpath:context-core.properties"/>

デフォルトでPlaceholderConfigurerは、aはフェイルファストになるため、プレースホルダーを解決できない場合は例外がスローされます。applicationContext.xmlファイルのインスタンスにはプロパティがないため、すべてのプレースホルダーで失敗します。

解決策:から1つを削除します それは物事を壊すだけなので何も追加しないので applicationContext.xmlます


素晴らしい、ありがとう、それで私は春にPlaceholderConfigurer?のインスタンスは1つしか存在できないと思います。
Mushtaq Jameel 2015年

11
いいえ、複数持つことはできませんが、プレースホルダーが見つからない場合、デフォルトではすぐに失敗します。あなたは、設定することで、これを無効にすることができますignore-unresolved-placeholderstrue
M. Deinum 2015年

3
アノテーション付きのSpringBootでどのように処理できますか?
rezKesh 2017年

5

私は同じ問題を抱えていました、追加することによってそれを解決しました

<filtering>true</filtering> 

pom.xml内:

以前(動作しませんでした):

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>               
        </resource>
    </resources>
</build>

後(うまくいった):

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

その後、mvn cleaninstallを実行してアプリケーションをデプロイします。


おかげで、これは私の問題を解決しました。しかし、なぜ/どのようにMavenリソースプラグインが春のプレースホルダーに影響を与えるのか興味があります...それらが関連しているとは思いもしませんでした!
PimHazebroek20年

3

この問題は、アプリケーションがsome_file_name.propertiesファイルにアクセスできない場合に発生します。春にプロパティファイルがresourcesフォルダーの下に配置されていることを確認してください。

トラブルシューティングの手順

1:リソースフォルダーの下にプロパティファイルを追加します。

2:リソースフォルダがない場合。プロジェクトの新規>ソースフォルダを右クリックし、リソースとして名前を付け、その下にプロパティファイルを配置して、新規に移動して作成します。

注釈ベースの実装の場合

追加@PropertySource(ignoreResourceNotFound = true, value = "classpath:some_file_name.properties")//プレースホルダーを使用する前に追加

例:

Assignment1Controller.Java

@PropertySource(ignoreResourceNotFound = true, value = "classpath:assignment1.properties")
@RestController  
public class Assignment1Controller {

//  @Autowired
//  Assignment1Services assignment1Services;
    @Value("${app.title}")
    private String appTitle;
     @RequestMapping(value = "/hello")  
        public String getValues() {

          return appTitle;

        }  

}

Assignment1.properties

app.title=Learning Spring

1
これはSpring4以降に適用されますか?
マルココグル

はい@Malkocoglu
ガニ

3

私の場合、application.ymlファイルをマージするときに不注意で、プロパティを右側に不必要にインデントしました。

私はそれを次のようにインデントしました:

spring:
    application:
       name: applicationName
............................
    myProperties:
       property1: property1value

コードはそれが次のようになることを期待していましたが:

spring:
    application:
        name: applicationName
.............................
myProperties:
    property1: property1value

3

デフォルト値を試すこともできます。春の値の注釈

定義されていない可能性のあるプロパティには、デフォルト値を指定できます。この例では、「somedefault」という値が挿入されます。

@Value("${unknown.param:some default}")
private String someDefault;

同じプロパティがシステムプロパティとしてプロパティファイルで定義されている場合、システムプロパティが適用されます。


わかりました...これは私を助けました。実際、私のアプリには多くのアプリケーション-<profile> .ymlファイルがあり、メイン構成で定義された新しいプロパティが原因でエラーが発生していました。ファイルのみ。正直なところ、メイン構成で値を1回だけ定義し、場合によってはプロファイル固有の構成で値をオーバーライドすることを期待していました。そのようには機能しないようです。デフォルト値を常に指定する必要があります。これで、プロパティをデフォルト値で初期化しなかったときに、Java構成が失敗した理由がわかりました。この動作を変更できますか?ありがとう:
Funder7 2020年

3

プログラムで@Valueアノテーションを宣言するたびに、マイクロサービスで同じエラーが発生しました。つまり、@ Value( "$ {project.api.key}")

同じ値のapplication.propertiesファイルが空白にならないようにしてくださいproject.api.key =いくつかの値を追加します

MostIMP:それ以外の場合は、「 'ServiceFTP'という名前のBeanの作成エラー:自動配線された依存関係の挿入」というエラーがスローされます。


0

スプリングブーツ付き:

pom.xml内

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <addResources>true</addResources>
            </configuration>
        </plugin>
    </plugins>
</build>

クラスJavaの例

@Configuration
@Slf4j
public class MyAppConfig {
    @Value("${foo}")
    private String foo;
    @Value("${bar}")
    private String bar;
    @Bean("foo")
    public String foo() {
        log.info("foo={}", foo);
        return foo;
    }
    @Bean("bar")
    public String bar() {
        log.info("bar={}", bar);
        return bar;
    }
    [ ... ]

プロパティファイル内:

src / main / resources / application.properties

foo=all-env-foo

src / main / resources / application-rec.properties

bar=rec-bar

src / main / resources / application-prod.properties

bar=prod-bar

Application.javaのVM引数内

-Dspring.profiles.active=[rec|prod]

プロパティを変更した後、mvnコマンドを実行することを忘れないでください!

mvn clean package -Dmaven.test.skip=true

-Dspring.profiles.active = recのログファイル:

The following profiles are active: rec
foo=all-env-foo
bar=rec-bar

-Dspring.profiles.active = prodのログファイル:

The following profiles are active: prod
foo=all-env-foo
bar=prod-bar

-Dspring.profiles.active = localのログファイル:

Could not resolve placeholder 'bar' in value "${bar}"

おっと、application-local.propertiesを作成するのを忘れています。


0

マイクロサービスプロジェクトで同じエラーが発生しました.ymlファイルでプロパティ自体が欠落しているため、問題を解決するプロパティ名と値を追加しました


0

このエラーは、Springプロジェクトがファイルプロパティ(bootstrap.ymlまたはapplication.yml)を読み取らないために表示されます。これを解決するには、pom.xmlに依存関係を追加する必要があります

   <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-context</artifactId>
    </dependency>

0

IntelliJ IDEAを使用して見つけることができなかったいくつかのカスタムプロパティでこの問題に頻繁に遭遇します-おそらくブランチ変更した後です。

私の場合に役立つのは

ファイル->キャッシュの無効化/再起動

IDEの問題よりもGradleのキャッシュの問題である可能性が高いと思いましたが、。/ gradlecleanは役に立ちませんでした



-3

私の解決策は、$と{の間にスペースを追加することでした。

例えば:

@Value("${project.ftp.adresse}")

になります

@Value("$ {project.ftp.adresse}")
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.