304

アノテーションを介してクラスパスから取得されるSpring Beanがたくさんあります。

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

Spring XML ファイルには、PropertyPlaceholderConfigurerが定義されています。

<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?

4

18 に答える 18

299

ELサポートを使用してSpring3でこれを行うことができます。例:

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

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

systemPropertiesは暗黙のオブジェクトでstrategyBeanあり、Bean名です。

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

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

これは私がもう少し情報のためにこれについて書いたブログ投稿です。

于 2008-12-04T07:41:12.197 に答える
149

個人的には、Spring 3.0の docs の新しい方法が気に入っています。

private @Value("${propertyName}") String propertyField;

ゲッターもセッターもありません!

構成を介してプロパティがロードされている場合:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
      p:location="classpath:propertyFile.properties" name="propertiesBean"/>

さらに嬉しいことに、IntelliJ で EL 式のクリックを制御することもでき、それによってプロパティ定義にたどり着きます!

完全に非xmlバージョンもあります:

@PropertySource("classpath:propertyFile.properties")
public class AppConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
于 2011-10-06T14:02:59.783 に答える
123

Spring 3.0.0M3@Valueには新しいアノテーションがあります。式だけでなくプレースホルダーもサポート@Value#{...}${...}

于 2009-07-28T09:05:41.717 に答える
31

<context:property-placeholder ... />PropertyPlaceholderConfigurer に相当する XML です。

例: applicationContext.xml

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

コンポーネント クラス

 private @Value("${propertyName}") String propertyField;
于 2012-10-31T15:19:05.967 に答える
15

もう 1 つの方法は、以下に示す appProperties Bean を追加することです。

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


<bean id="appProperties" 
          class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="singleton" value="true"/>

        <property name="properties">
                <props>
                        <prop key="results.max">${results.max}</prop>
                </props>
        </property>
</bean>

取得すると、この Bean を にキャストできます。これには、値が から読み取られるjava.util.Propertiesという名前のプロパティが含まれます。繰り返しになりますが、この Bean は、@Resource アノテーションを介して任意のクラスに (java.util.Properties のインスタンスとして) 依存関係を注入できます。results.maxapp.properties

個人的には、appProperties によって公開されるプロパティを正確に制限でき、app.properties を 2 回読み取る必要がないため、このソリューションを (私が提案した他のソリューションよりも) 好みます。

于 2008-11-25T17:25:27.383 に答える
9

2つのプロパティファイルが必要です。1つは本番用で、もう1つは開発用のオーバーライドです(デプロイされません)。

自動配線可能なプロパティBeanとPropertyConfigurerの両方を使用するには、次のように記述します。

<bean id="appProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="singleton" value="true" />

    <property name="ignoreResourceNotFound" value="true" />
    <property name="locations">
        <list>
            <value>classpath:live.properties</value>
            <value>classpath:development.properties</value>
        </list>
    </property>
</bean>

PropertyConfigurerでプロパティBeanを参照します

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="properties" ref="appProperties" />
</bean>
于 2008-11-26T07:19:32.833 に答える
8

クラスに注釈を付けることもできます:

@PropertySource("classpath:/com/myProject/config/properties/database.properties")

そして、次のような変数があります。

@Autowired
private Environment env;

これで、次の方法ですべてのプロパティにアクセスできます。

env.getProperty("database.connection.driver")
于 2015-01-09T20:01:27.893 に答える
7

アノテーションを使用してプロパティ定数をBeanに直接挿入できるSpring3を入手する前に、同じことを行うPropertyPlaceholderConfigurerBeanのサブクラスを作成しました。したがって、プロパティセッターをマークアップすると、Springは次のようにプロパティをBeanに自動配線します。

@Property(key="property.key", defaultValue="default")
public void setProperty(String property) {
    this.property = property;
}

注釈は次のとおりです。

@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface Property {
    String key();
    String defaultValue() default "";
}

PropertyAnnotationAndPlaceholderConfigurerは次のとおりです。

public class PropertyAnnotationAndPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

    private static Logger log = Logger.getLogger(PropertyAnnotationAndPlaceholderConfigurer.class);

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties properties) throws BeansException {
        super.processProperties(beanFactory, properties);

        for (String name : beanFactory.getBeanDefinitionNames()) {
            MutablePropertyValues mpv = beanFactory.getBeanDefinition(name).getPropertyValues();
            Class clazz = beanFactory.getType(name);

            if(log.isDebugEnabled()) log.debug("Configuring properties for bean="+name+"["+clazz+"]");

            if(clazz != null) {
                for (PropertyDescriptor property : BeanUtils.getPropertyDescriptors(clazz)) {
                    Method setter = property.getWriteMethod();
                    Method getter = property.getReadMethod();
                    Property annotation = null;
                    if(setter != null && setter.isAnnotationPresent(Property.class)) {
                        annotation = setter.getAnnotation(Property.class);
                    } else if(setter != null && getter != null && getter.isAnnotationPresent(Property.class)) {
                        annotation = getter.getAnnotation(Property.class);
                    }
                    if(annotation != null) {
                        String value = resolvePlaceholder(annotation.key(), properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
                        if(StringUtils.isEmpty(value)) {
                            value = annotation.defaultValue();
                        }
                        if(StringUtils.isEmpty(value)) {
                            throw new BeanConfigurationException("No such property=["+annotation.key()+"] found in properties.");
                        }
                        if(log.isDebugEnabled()) log.debug("setting property=["+clazz.getName()+"."+property.getName()+"] value=["+annotation.key()+"="+value+"]");
                        mpv.addPropertyValue(property.getName(), value);
                    }
                }

                for(Field field : clazz.getDeclaredFields()) {
                    if(log.isDebugEnabled()) log.debug("examining field=["+clazz.getName()+"."+field.getName()+"]");
                    if(field.isAnnotationPresent(Property.class)) {
                        Property annotation = field.getAnnotation(Property.class);
                        PropertyDescriptor property = BeanUtils.getPropertyDescriptor(clazz, field.getName());

                        if(property.getWriteMethod() == null) {
                            throw new BeanConfigurationException("setter for property=["+clazz.getName()+"."+field.getName()+"] not available.");
                        }

                        Object value = resolvePlaceholder(annotation.key(), properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
                        if(value == null) {
                            value = annotation.defaultValue();
                        }
                        if(value == null) {
                            throw new BeanConfigurationException("No such property=["+annotation.key()+"] found in properties.");
                        }
                        if(log.isDebugEnabled()) log.debug("setting property=["+clazz.getName()+"."+field.getName()+"] value=["+annotation.key()+"="+value+"]");
                        mpv.addPropertyValue(property.getName(), value);
                    }
                }
            }
        }
    }

}

好みに合わせて自由に変更してください

于 2009-02-23T11:08:44.650 に答える
5

考えられる解決策は、同じプロパティ ファイルから読み取る 2 番目の Bean を宣言することです。

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

<util:properties id="appProperties" location="classpath:/WEB-INF/app.properties"/>

「appProperties」という名前の Bean のタイプは java.util.Properties であり、上記の @Resource 属性を使用して依存関係を注入できます。

于 2008-11-25T17:22:27.717 に答える
4

Spring 2.5 の使用に行き詰まっている場合は、プロパティごとに Bean を定義し、修飾子を使用してそれらを注入できます。このような:

  <bean id="someFile" class="java.io.File">
    <constructor-arg value="${someFile}"/>
  </bean>

@Service
public class Thing
      public Thing(@Qualifier("someFile") File someFile) {
...

とても読みやすいわけではありませんが、仕事は完了します。

于 2009-12-17T14:28:28.540 に答える
2

Spring Bean へのプロパティ値の自動配線:

ほとんどの人は、@Autowired を使用して、Spring がアプリケーション コンテキストをロードするときに、あるオブジェクトを別のオブジェクトに注入するように指示できることを知っています。あまり知られていない情報として、@Value アノテーションを使用してプロパティ ファイルの値を Bean の属性に注入することもできます。詳細については、この投稿を参照してください...

|| Spring 3.0 の新機能 || ビーン値の自動配線 || 春の自動配線プロパティ値

于 2013-01-02T12:39:35.360 に答える
0

構成にさらに柔軟性が必要な場合は、Settings4jPlaceholderConfigurer を試してください: http://settings4j.sourceforge.net/currentrelease/configSpringPlaceholder.html

私たちのアプリケーションでは、以下を使用します。

  • PreProd-System および Prod-System を構成する設定
  • 「mvn jetty:run」の設定と JNDI 環境変数 (JNDI が設定を上書きします)
  • UnitTests のシステム プロパティ (@BeforeClass アノテーション)

key-value-Source が最初にチェックされるデフォルトの順序は、http:
//settings4j.sourceforge.net/currentrelease/configDefault.html
で説明されています。クラスパス。

ご意見をお聞かせください: settings4j-user@lists.sourceforge.net

よろしくお願いします、
ハラルド

于 2013-03-13T18:05:50.813 に答える
0

Spring 5 で最も簡単な方法は、@ConfigurationPropertiesここで 使用することですhttps://mkyong.com/spring-boot/spring-boot-configurationproperties-example/の例です

于 2020-06-29T08:11:11.607 に答える
-1

Spring の「PropertyPlaceholderConfigurer」クラスを使用する

Bean のプロパティとして動的に読み取られるプロパティ ファイルを示す簡単な例

<bean id="placeholderConfig"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>/WEB-INF/classes/config_properties/dev/database.properties</value>
        </list>
    </property> 
</bean>

<bean id="devDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="${dev.app.jdbc.driver}"/>
    <property name="jdbcUrl" value="${dev.app.jdbc.url}"/>
    <property name="user" value="${dev.app.jdbc.username}"/>
    <property name="password" value="${dev.app.jdbc.password}"/>
    <property name="acquireIncrement" value="3"/>
    <property name="minPoolSize" value="5"/>
    <property name="maxPoolSize" value="10"/>
    <property name="maxStatementsPerConnection" value="11000"/>
    <property name="numHelperThreads" value="8"/>
    <property name="idleConnectionTestPeriod" value="300"/>
    <property name="preferredTestQuery" value="SELECT 0"/>
</bean> 

プロパティファイル

dev.app.jdbc.driver=com.mysql.jdbc.Driver

dev.app.jdbc.url=jdbc:mysql://localhost:3306/addvertisement

dev.app.jdbc.username=ルート

dev.app.jdbc.password=ルート

于 2014-04-19T16:52:27.497 に答える