Spring 如何从属性文件中读取值?

Spring 如何从属性文件中读取值?,spring,properties-file,Spring,Properties File,我用的是弹簧。我需要从属性文件中读取值。这是内部属性文件,而不是外部属性文件。属性文件可以如下所示 some.properties ---file name. values are below. abc = abc def = dsd ghi = weds jil = sdd 我需要以非传统方式从属性文件中读取这些值。如何实现?spring 3.0有什么最新的方法吗?您需要在应用程序上下文中放置一个PropertyPlaceholderConfigurer bean,并设置其location

我用的是弹簧。我需要从属性文件中读取值。这是内部属性文件,而不是外部属性文件。属性文件可以如下所示

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

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

我需要以非传统方式从属性文件中读取这些值。如何实现?spring 3.0有什么最新的方法吗?

您需要在应用程序上下文中放置一个PropertyPlaceholderConfigurer bean,并设置其location属性

详情如下:

您可能需要修改一点属性文件才能使其正常工作


希望有帮助。

在您的上下文中配置PropertyPlaceholder:

<context:property-placeholder location="classpath*:my.properties"/>
要分析具有多个逗号分隔值的属性,请执行以下操作:

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>
在配置类中

@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;
   }
}

以下是另外一个答案,这对我理解它的工作原理也有很大帮助:

任何BeanFactoryPostProcessor bean都必须使用static修饰符声明

[项目结构]:http://i.stack.imgur.com/RAGX3.jpg
-------------------------------
包装豆;
导入java.util.Properties;
导入java.util.Set;
公共类属性bean{
私人物业;;
公共void集合属性(属性){
这个。属性=属性;
}
public void getProperty(){
Set keys=properties.keySet();
用于(对象关键点:关键点){
System.out.println(key+”:“+properties.getProperty(key.toString());
}
}
}
----------------------------
包装豆;
导入org.springframework.context.ApplicationContext;
导入org.springframework.context.support.ClassPathXmlApplicationContext;
公开课考试{
公共静态void main(字符串[]args){
//TODO自动生成的方法存根
ApplicationContext ap=new ClassPathXmlApplicationContext(“resource/spring.xml”);
PropertiesBeans p=(PropertiesBeans)ap.getBean(“p”);
p、 getProperty();
}
}
----------------------------
-驱动程序属性
Driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
用户名=根
密码=根
----------------------------

实现这一目标有多种方法。下面是一些在春天常用的方法-

  • 使用PropertyPlaceHolderConfigure

  • 使用PropertySource

  • 使用ResourceBundleMessageSource

  • 使用PropertiesFactoryBean

    还有更多

  • 假设
    ds.type
    是属性文件中的键


    使用
    属性PlaceHolderConfigure

    注册
    PropertyPlaceholderConfigurer
    bean-

    <context:property-placeholder location="classpath:path/filename.properties"/>
    
    注册
    属性资源占位符配置器后,可以访问该值-

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

    使用
    PropertySource

    在最新的spring版本中,您不需要向
    @PropertySource
    注册
    propertyplaceholderconfigure
    ,我发现了一个很好的版本兼容性-

    @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>
    
    <bean id="properties"
          class="org.springframework.beans.factory.config.PropertiesFactoryBean">
      <property name="locations">
        <list>
          <value>classpath:path/filename.properties</value>
        </list>
      </property>
    </bean>
    


    使用
    属性FactoryBean

    注册Bean-

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

    如果您需要在不使用@Value的情况下手动读取属性文件。

    感谢Lokesh Gupta写得很好的一页:

    package-utils;
    导入org.slf4j.Logger;
    导入org.slf4j.LoggerFactory;
    导入org.springframework.util.ResourceUtils;
    导入java.io.FileInputStream;
    导入java.io.IOException;
    导入java.io.InputStream;
    导入java.util.Properties;
    导入java.io.File;
    公共类UTIL{
    私有静态最终记录器Logger=LoggerFactory.getLogger(Utils.class.getName());
    公共静态属性fetchProperties(){
    属性=新属性();
    试一试{
    File File=ResourceUtils.getFile(“classpath:application.properties”);
    InputStream in=新文件InputStream(文件);
    属性。荷载(in);
    }捕获(IOE异常){
    LOGGER.error(例如getMessage());
    }
    归还财产;
    }
    }
    
    我建议您阅读SpringBoot文档中有关注入外部配置的链接。他们不仅讨论了从属性文件中检索,还讨论了YAML甚至JSON文件。我觉得这很有帮助。我希望你也是

    另一种方法是使用。基本上,您可以使用包的名称而不使用“.properties”

    private static final ResourceBundle resource = ResourceBundle.getBundle("config");
    
    您可以使用以下方法恢复任何值:

    private final String prop = resource.getString("propName");
    

    我想要一个不是由spring管理的实用程序类,因此没有像
    @Component
    @Configuration
    等spring注释。但我希望该类从
    应用程序读取。属性

    我通过让类了解Spring上下文,从而了解
    环境
    ,从而使
    环境.getProperty()

    明确地说,我有:

    应用程序属性

    mypath=somestring
    
    Utils.java

    import org.springframework.core.env.Environment;
    
    // No spring annotations here
    public class Utils {
        public String execute(String cmd) {
            // Making the class Spring context aware
            ApplicationContextProvider appContext = new ApplicationContextProvider();
            Environment env = appContext.getApplicationContext().getEnvironment();
    
            // env.getProperty() works!!!
            System.out.println(env.getProperty("mypath")) 
        }
    }
    
    ApplicationContextProvider.java(请参阅)


    这看起来不像一个文件。如果它是Java意义上的属性文件-是。否则,它是一种需要区别对待的自定义文件格式(如果没有键,您不能在Spring中将这些行用作属性值)。“不是以传统方式”-这是什么意思?我的意思是使用注释..而不是xml配置..嗨,mrembisz,感谢您的回复。我爱你
    @Component
    public class BeanTester {
        @Autowired MessageSource messageSource; 
        public void execute() {
            String attr = this.messageSource.getMessage("ds.type", null, null);
        }
    }
    
    <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");
        }
    }
    
    private static final ResourceBundle resource = ResourceBundle.getBundle("config");
    
    private final String prop = resource.getString("propName");
    
    mypath=somestring
    
    import org.springframework.core.env.Environment;
    
    // No spring annotations here
    public class Utils {
        public String execute(String cmd) {
            // Making the class Spring context aware
            ApplicationContextProvider appContext = new ApplicationContextProvider();
            Environment env = appContext.getApplicationContext().getEnvironment();
    
            // env.getProperty() works!!!
            System.out.println(env.getProperty("mypath")) 
        }
    }
    
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.stereotype.Component;
    
    @Component
    public class ApplicationContextProvider implements ApplicationContextAware {
        private static ApplicationContext CONTEXT;
    
        public ApplicationContext getApplicationContext() {
            return CONTEXT;
        }
    
        public void setApplicationContext(ApplicationContext context) throws BeansException {
            CONTEXT = context;
        }
    
        public static Object getBean(String beanName) {
            return CONTEXT.getBean(beanName);
        }
    }