Spring Framework 5のBeanライフサイクル管理と拡張機能

Beanのライフサイクル

オブジェクトのライフサイクルとは、生成、生存、破棄の完全なプロセスを指します。Springがオブジェクトの管理を担当するため、ライフサイクル理解は重要です。

ライフサイクルの3段階

生成段階:

  • scope="singleton": アプリケーションコンテキスト生成時にオブジェクトを生成
  • scope="prototype": getBean()呼び出し時にオブジェクトを生成

初期化段階:

<!-- InitializingBeanインターフェース実装 -->
public class DataInitializer implements InitializingBean {
    public void afterPropertiesSet() {
        // 初期化ロジック
    }
}

<!-- カスタム初期化メソッド -->
<bean id="service" init-method="setupResources" class="com.example.Service"/>
初期化操作順序: 1. InitializingBean 2. カスタムメソッド。リソース初期化(DB/ネットワーク)に使用します。

破棄段階:

// DisposableBean実装
public class ResourceCleaner implements DisposableBean {
    public void destroy() {
        // リソース解放
    }
}

<!-- カスタム破棄メソッド -->
<bean id="connector" destroy-method="release" class="com.example.DBConnector"/>
破棄操作はsingletonスコープのみ有効で、リソース解放(接続クローズ等)を実行します。

設定ファイルのパラメータ化

頻繁に変更される設定値(DB接続情報等)を.propertiesファイルに分離:

# database.properties
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/appdb
db.user=admin
db.password=securePass123

Spring設定ファイルとの統合:

<context:property-placeholder location="classpath:database.properties"/>
<bean id="dataSource" class="com.example.DataSource">
    <property name="url" value="${db.url}"/>
</bean>

カスタム型コンバーター

Springが提供しない型変換を実装:

public class DateFormatConverter implements Converter<String, Date> {
    private String dateFormat;
    
    public void setDateFormat(String format) {
        this.dateFormat = format;
    }
    
    public Date convert(String source) {
        try {
            return new SimpleDateFormat(dateFormat).parse(source);
        } catch (ParseException e) {
            throw new IllegalArgumentException("Invalid date format");
        }
    }
}

Spring設定:

<bean id="dateConverter" class="com.example.DateFormatConverter">
    <property name="dateFormat" value="yyyy-MM-dd"/>
</bean>

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <ref bean="dateConverter"/>
        </set>
    </property>
</bean>

BeanPostProcessorによる後処理

Bean生成後の加工処理を実装:

public class CustomBeanProcessor implements BeanPostProcessor {
    public Object postProcessAfterInitialization(Object bean, String name) {
        if (bean instanceof Product) {
            Product product = (Product) bean;
            product.setCategory("ELECTRONICS");
        }
        return bean;
    }
}

設定ファイル登録:

<bean class="com.example.CustomBeanProcessor"/>
全Beanに適用されるため、対象を限定する必要があります。

タグ: SpringFramework BeanLifecycle TypeConversion BeanPostProcessor configuration

7月26日 03:17 投稿