简体   繁体   English

Spring - 从属性文件中检索值

[英]Spring - Retrieve value from properties file

I have the following configuration in my applicationContext.xml: 我的applicationContext.xml中有以下配置:

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

Now, in my java class, how can I read the values from the file app.properties? 现在,在我的java类中,如何从app.properties文件中读取值?

With Spring 3.0 you can use the @Value annotation. 使用Spring 3.0,您可以使用@Value注释。

@Component
class MyComponent {

  @Value("${valueKey}")
  private String valueFromPropertyFile;
}

Actually PropertyPlaceholderConfigurer is useful to inject values to spring context using properties. 实际上,PropertyPlaceholderConfigurer对于使用属性将值注入spring上下文非常有用。

Example XML context definition: 示例XML上下文定义:

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
   <property name="driverClassName"><value>${driver}</value></property>
   <property name="url"><value>jdbc:${dbname}</value></property>
</bean>`

Example properties file: 示例属性文件:

driver=com.mysql.jdbc.Driver
dbname=mysql:mydb

Or you can create bean like 或者你可以像创建bean一样

<bean name="myBean" value="${some.property.key}" /> 

and then inject this bean into your class 然后将此bean注入您的类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在春季使用自动装配从属性文件中检索键的值 - How to retrieve the value of a key from properties file in spring using Autowiring 无法使用Spring的@Value,@ ConfigurationProperties注释从Properties文件中检索值 - Unable to retrieve value from Properties file using Spring's @Value, @ConfigurationProperties annotations 如何使用 spring 从属性文件中检索值 - How to retrieve values from a properties file using spring 春季:属性文件中的值未自动装配 - Spring: Value from a properties file is not autowired 来自属性文件的Java Spring Maven值 - Java Spring Maven value from properties file 在Spring Framework View中显示属性文件中的值(.jsp文件)? - Displaying value from properties file in a Spring Framework View (.jsp file)? Spring Boot 应用程序在 main 方法中从属性文件中读取值 - Spring Boot application to read a value from properties file in main method 如何使用Spring在运行时从属性文件获取键值 - How to get key value from properties file at runtime using spring 从属性文件中读取列表并加载弹簧注释 @Value - Reading a List from properties file and load with spring annotation @Value 从属性文件中读取Map并使用spring注释加载@Value - Reading a Map from properties file and load with spring annotation @Value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM