SpringアプリのpropertiesにあるBoolean値をStringだと間違われる問題

投稿日:

更新日:

カテゴリ:

Spring BootアプリでTypeMismatchExceptionが発生し、application.propertiesに書いてあるfalse値をStringからBooleanに変換できないことで怒られています。@EnableAutoConfigurationを付けたら問題が解消されることは分かりましたが、ブラックボックスのままにはして置きたくないですね。手動で設定するにはどうしたら良いでしょうか。

概要

発生したTypeMismatchExceptionは次のようになります。

Caused by: org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Boolean';

Springアプリに@EnableAutoConfigurationを付けたら、application.propertiesにlogging.level.root=DEBUGを追加にすると、PropertySourcesPlaceholderConfigurerというクラスを自動的に設定値を見つけて変換していることを確認してます。これの手動で設定する方法、特にXMLでの書き方にについて知りたかったです。

解決方法

1時間ぐらい調べても、やり方が見つからず、今日はもうやめようと思ったところ、ChatGPTに聞いてました。
そしたら、正解かどうかは要確認ですが、それらしい回答をもらいました。

Javaで書く場合:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

@Configuration
public class MyConfiguration {

    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
        Resource[] resources = new ClassPathResource[]{new ClassPathResource("application.properties")};
        pspc.setLocations(resources);
        pspc.setIgnoreUnresolvablePlaceholders(true);
        return pspc;
    }

}

XMLで書く場合:

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

    <context:property-placeholder location="classpath:application.properties" ignore-unresolvable="true"/>

</beans>

<context:property-placeholder>を見た瞬間、あっ!これじゃん〜他のところで見たことがある!と思いました。

いやあぁ、ChatGPTの有料会員になろうかな〜
自分の職が危うい気もしてきます。。

追記

2023/03/09
動作確認は取れました。application.propertiesなら、次のだけで行けました。

<context:property-placeholder />

投稿日

カテゴリー:

投稿者:

タグ:

コメント

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です