アノテーションを使用して構成された Spring Bean にプロパティ値を挿入するにはどうすればよいですか? 質問する

アノテーションを使用して構成された Spring Bean にプロパティ値を挿入するにはどうすればよいですか? 質問する

私はアノテーションを介してクラスパスから取得されるSpring Beanをいくつか持っています。例えば

@Repository("personDao")
public class PersonDaoImpl extends AbstractDaoImpl implements PersonDao {
    // Implementation omitted
}

Spring XMLファイルには、プロパティプレースホルダーコンフィギュレーター定義:

<bean id="propertyConfigurer" 
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="/WEB-INF/app.properties" />
</bean> 

app.properitesのプロパティの1つを上記のBeanに挿入したいのですが、次のように単純に行うことはできません。

<bean class="com.example.PersonDaoImpl">
    <property name="maxResults" value="${results.max}"/>
</bean>

PersonDaoImpl は Spring XML ファイルには含まれていないため (アノテーションを介してクラスパスから取得されます)、次のことがわかりました。

@Repository("personDao")
public class PersonDaoImpl extends AbstractDaoImpl implements PersonDao {

    @Resource(name = "propertyConfigurer")
    protected void setProperties(PropertyPlaceholderConfigurer ppc) {
    // Now how do I access results.max? 
    }
}

しかし、興味のある物件にどうやってアクセスすればいいのか分かりませんppc

ベストアンサー1

Spring 3 では EL サポートを使用してこれを実行できます。例:

@Value("#{systemProperties.databaseName}")
public void setDatabaseName(String dbName) { ... }

@Value("#{strategyBean.databaseKeyGenerator}")
public void setKeyGenerator(KeyGenerator kg) { ... }

systemProperties暗黙的なオブジェクトであり、strategyBeanBean 名です。

もう 1 つの例は、オブジェクトからプロパティを取得するときに機能します。また、フィールドにProperties適用できることも示しています。@Value

@Value("#{myProperties['github.oauth.clientId']}")
private String githubOauthClientId;

がここにありますブログ投稿もう少し詳しい情報を得るためにこれについて書きました。

おすすめ記事