Как прочитать значения из файла свойств? - PullRequest
117 голосов
/ 13 февраля 2012

Я использую весну.Мне нужно прочитать значения из файла свойств.Это внутренний файл свойств, а не внешний файл свойств.Файл свойств может быть как ниже.

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

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

Мне нужно прочитать эти значения из файла свойств не традиционным способом.Как этого добиться?Есть ли какой-нибудь последний подход с пружиной 3.0?

Ответы [ 9 ]

186 голосов
/ 13 февраля 2012

Настройте 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>

и bean-компонент:

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

  @PostConstruct
  public void init() {
    // do whatever you need with properties
  }
}
40 голосов
/ 17 апреля 2013

В классе конфигурации

@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;
   }
}
39 голосов
/ 27 января 2017

Существуют различные способы достижения того же. Ниже приведены некоторые часто используемые способы весной-

  1. Использование PropertyPlaceholderConfigurer
  2. Использование PropertySource
  3. Использование ResourceBundleMessageSource
  4. Использование PropertiesFactoryBean

    и многие другие ........................

Предполагая, что ds.type является ключом в вашем файле свойств.


Использование PropertyPlaceholderConfigurer

Регистрация PropertyPlaceholderConfigurer bean-

<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

Register 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

Register Bean-

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

Экземпляр свойств провода в ваш класс-

@Component
public class BeanTester {
    @Autowired Properties properties; 
    public void execute() {
        String attr = properties.getProperty("ds.type");
    }
}
25 голосов
/ 21 августа 2013

Вот еще один ответ, который также помог мне понять, как это работает: http://www.javacodegeeks.com/2013/07/spring-bean-and-propertyplaceholderconfigurer.html

любые bean-компоненты BeanFactoryPostProcessor должны быть объявлены с 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();
 }
}
7 голосов
/ 24 марта 2018

Если вам нужно вручную прочитать файл свойств, не используя @ Value.

Спасибо за хорошо написанную страницу Локеша Гупта: Блог

enter image description here

package utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.io.File;


public class Utils {

    private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class.getName());

    public static Properties fetchProperties(){
        Properties properties = new Properties();
        try {
            File file = ResourceUtils.getFile("classpath:application.properties");
            InputStream in = new FileInputStream(file);
            properties.load(in);
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
        return properties;
    }
}
6 голосов
/ 13 февраля 2012

Вам необходимо поместить bean-компонент PropertyPlaceholderConfigurer в контекст приложения и установить его свойство location.

См. Подробности здесь: http://www.zparacha.com/how-to-read-properties-file-in-spring/

Возможно, вам придется немного изменить файл свойств дляэта штука работает.

Надеюсь, это поможет.

1 голос
/ 15 ноября 2018

Другой способ - использование ResourceBundle В основном вы получаете пакет, используя его имя без '.properties'

private static final ResourceBundle resource = ResourceBundle.getBundle("config");

И вы восстанавливаете любое значение, используя это:

private final String prop = resource.getString("propName");
0 голосов
/ 03 апреля 2018

Я рекомендую прочитать эту ссылку https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html из документации SpringBoot о внедрении внешних конфигов.Они говорили не только о получении из файла свойств, но также о файлах YAML и даже JSON.Я нашел это полезным.Я надеюсь, что вы тоже.

0 голосов
/ 26 августа 2016
 [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>
...