142

スプリングを使用しています。プロパティ ファイルから値を読み取る必要があります。これは、外部プロパティ ファイルではなく、内部プロパティ ファイルです。プロパティファイルは次のようになります。

some.properties ---file name. values are below.

abc = abc
def = dsd
ghi = weds
jil = sdd

従来の方法ではなく、プロパティ ファイルからこれらの値を読み取る必要があります。それを達成する方法は?spring 3.0 の最新のアプローチはありますか?

4

10 に答える 10

205

コンテキストで PropertyPlaceholder を構成します。

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

次に、Bean のプロパティを参照します。

@Component
class MyClass {
  @Value("${my.property.name}")
  private String[] myValues;
}

複数のコンマ区切り値でプロパティを解析するには:

my.property.name=aaa,bbb,ccc

それがうまくいかない場合は、Bean をプロパティで定義し、手動で注入して処理することができます。

<bean id="myProperties"
      class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="locations">
    <list>
      <value>classpath*:my.properties</value>
    </list>
  </property>
</bean>

そして豆:

@Component
class MyClass {
  @Resource(name="myProperties")
  private Properties myProperties;

  @PostConstruct
  public void init() {
    // do whatever you need with properties
  }
}
于 2012-02-13T12:37:01.860 に答える
53

同じことを達成するためのさまざまな方法があります。以下は、春に一般的に使用されるいくつかの方法です-

  1. PropertyPlaceholderConfigurer の使用

  2. PropertySource の使用

  3. ResourceBundleMessageSource の使用

  4. PropertiesFactoryBean の使用

    などなど........................

ds.typeプロパティファイルのキーであると仮定します。


使用するPropertyPlaceholderConfigurer

PropertyPlaceholderConfigurerBean を登録します。

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

また

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations" value="classpath:path/filename.properties" ></property>
</bean>

また

@Configuration
public class SampleConfig {
 @Bean
 public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
  return new PropertySourcesPlaceholderConfigurer();
  //set locations as well.
 }
}

登録後PropertySourcesPlaceholderConfigurer、値にアクセスできます-

@Value("${ds.type}")private String attr; 

使用するPropertySource

PropertyPlaceHolderConfigurerに登録する必要のない最新の春のバージョンでは、バージョンの互換性を理解するため@PropertySourceの良いリンクを見つけました-

@PropertySource("classpath:path/filename.properties")
@Component
public class BeanTester {
    @Autowired Environment environment; 
    public void execute() {
        String attr = this.environment.getProperty("ds.type");
    }
}

使用するResourceBundleMessageSource

Bean を登録します。

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
  <property name="basenames">
    <list>
      <value>classpath:path/filename.properties</value>
    </list>
  </property>
</bean>

アクセス値-

((ApplicationContext)context).getMessage("ds.type", null, null);

また

@Component
public class BeanTester {
    @Autowired MessageSource messageSource; 
    public void execute() {
        String attr = this.messageSource.getMessage("ds.type", null, null);
    }
}

使用するPropertiesFactoryBean

Bean を登録します。

<bean id="properties"
      class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="locations">
    <list>
      <value>classpath:path/filename.properties</value>
    </list>
  </property>
</bean>

Properties インスタンスをクラスに配線します-

@Component
public class BeanTester {
    @Autowired Properties properties; 
    public void execute() {
        String attr = properties.getProperty("ds.type");
    }
}
于 2017-01-26T21:26:07.843 に答える
49

構成クラスで

@Configuration
@PropertySource("classpath:/com/myco/app.properties")
public class AppConfig {
   @Autowired
   Environment env;

   @Bean
   public TestBean testBean() {
       TestBean testBean = new TestBean();
       testBean.setName(env.getProperty("testbean.name"));
       return testBean;
   }
}
于 2013-04-17T13:36:29.903 に答える
28

これがどのように機能するかを理解するのに大いに役立った追加の回答は次のとおりです

BeanFactoryPostProcessor Bean はすべてstatic、修飾子で宣言する必要があります

@Configuration
@PropertySource("classpath:root/test.props")
public class SampleConfig {
 @Value("${test.prop}")
 private String attr;
 @Bean
 public SampleService sampleService() {
  return new SampleService(attr);
 }

 @Bean
 public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
  return new PropertySourcesPlaceholderConfigurer();
 }
}
于 2013-08-21T07:29:02.360 に答える
6

PropertyPlaceholderConfigurer Beanをアプリケーションコンテキストに配置し、そのロケーションプロパティを設定する必要があります。

詳細はこちらをご覧ください:http ://www.zparacha.com/how-to-read-properties-file-in-spring/

これを機能させるには、プロパティファイルを少し変更する必要があるかもしれません。

それが役に立てば幸い。

于 2012-02-13T11:41:31.313 に答える
0
 [project structure]: http://i.stack.imgur.com/RAGX3.jpg
-------------------------------
    package beans;

        import java.util.Properties;
        import java.util.Set;

        public class PropertiesBeans {

            private Properties properties;

            public void setProperties(Properties properties) {
                this.properties = properties;
            }

            public void getProperty(){
                Set keys = properties.keySet();
                for (Object key : keys) {
                    System.out.println(key+" : "+properties.getProperty(key.toString()));
                }
            }

        }
    ----------------------------

        package beans;

        import org.springframework.context.ApplicationContext;
        import org.springframework.context.support.ClassPathXmlApplicationContext;

        public class Test {

            public static void main(String[] args) {
                // TODO Auto-generated method stub
                ApplicationContext ap = new ClassPathXmlApplicationContext("resource/spring.xml");
                PropertiesBeans p = (PropertiesBeans)ap.getBean("p");
                p.getProperty();
            }

        }
    ----------------------------

 - driver.properties

    Driver = com.mysql.jdbc.Driver
    url = jdbc:mysql://localhost:3306/test
    username = root
    password = root
    ----------------------------



     <beans xmlns="http://www.springframework.org/schema/beans"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:util="http://www.springframework.org/schema/util"
               xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

            <bean id="p" class="beans.PropertiesBeans">
                <property name="properties">
                    <util:properties location="classpath:resource/driver.properties"/>
                </property>
            </bean>

        </beans>
于 2016-08-26T07:01:08.417 に答える
0

外部構成の注入に関する SpringBoot ドキュメントのこのリンクhttps://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.htmlを読むことをお勧めします。彼らは、プロパティ ファイルからの取得についてだけでなく、YAML や JSON ファイルについても話しました。役に立ちました。私はあなたもそう願っています。

于 2018-04-03T06:34:21.843 に答える