如何访问Spring Boot中application.properties文件中定义的值

时间:2015-05-29 11:19:29

标签: java spring-boot properties-file

我想访问application.properties中提供的值,例如:

logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
logging.file=${HOME}/application.log

userBucket.path=${HOME}/bucket

我想在Spring Boot应用程序中访问主程序中的userBucket.path

26 个答案:

答案 0 :(得分:307)

您可以使用var answers = ["Hrtkovci", "Lepenica", "Dec"], correctAnswers = ["Lepenica", "Dec", "Leskovac"], count = 0, percent; correctAnswers.forEach(function (c) { if (answers.some(function (a) { return a === c; })) { count++; } }); percent = count * 100 / correctAnswers.length; document.write('Right Answers: '+count + ' Rate: ' + percent.toFixed(2) + ' %'); 注释并在您正在使用的任何一个Spring bean中访问该属性

@Value

Spring Boot文档的Externalized Configuration部分,解释了您可能需要的所有细节。

答案 1 :(得分:161)

Another way is injecting Environment to your bean.

@Autowired
private Environment env;
....

public void method() {
    .....  
    String path = env.getProperty("userBucket.path");
    .....
}

答案 2 :(得分:19)

@ConfigurationProperties可用于将.properties(也支持.yml)的值映射到POJO。

请考虑以下示例文件。

<强>的.properties

cust.data.employee.name=Sachin
cust.data.employee.dept=Cricket

<强> Employee.java

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@ConfigurationProperties(prefix = "cust.data.employee")
@Configuration("employeeProperties")
public class Employee {

    private String name;
    private String dept;

    //Getters and Setters go here
}

现在可以通过自动装配employeeProperties来访问属性值,如下所示。

@Autowired
private Employee employeeProperties;

public void method() {

   String employeeName = employeeProperties.getName();
   String employeeDept = employeeProperties.getDept();

}

答案 3 :(得分:5)

遵循以下步骤。 1:-创建您的配置类,如下所示

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;

@Configuration
public class YourConfiguration{

    // passing the key which you set in application.properties
    @Value("${userBucket.path}")
    private String userBucket;

   // getting the value from that key which you set in application.properties
    @Bean
    public String getUserBucketPath() {
        return userBucket;
    }
}

2:-当您拥有配置类时,请从所需的配置中注入变量。

@Component
public class YourService {

    @Autowired
    private String getUserBucketPath;

    // now you have a value in getUserBucketPath varibale automatically.
}

答案 4 :(得分:4)

当前, 我知道以下三种方式:

1。 @Value批注

    @Value("${<property.name>}")
    private static final <datatype> PROPERTY_NAME;
  • 根据我的经验,有些情况下您不 可以获取该值或将其设置为null。 例如, 当您尝试使用preConstruct()方法或init()方法进行设置时。 发生这种情况是因为在完全构造了类之后才进行了值注入。 这就是为什么最好使用3'rd选项的原因。

2。 @PropertySource批注

<pre>@PropertySource("classpath:application.properties")

//env is an Environment variable
env.getProperty(configKey);</pre>
  • PropertySouce会在加载类时在Environment变量(在您的类中)中从属性源文件中设置值。 这样您就可以轻松获取后记。
    • 可通过系统环境变量访问。

3。 @ConfigurationProperties批注。

  • 这通常在Spring项目中用于加载配置属性。
  • 它基于属性数据初始化实体。

    • @ConfigurationProperties标识要加载的属性文件。
    • @Configuration基于配置文件变量创建一个bean。
    @ConfigurationProperties(prefix = "user")
    @Configuration("UserData")
    class user {
      //Property & their getter / setter
    }
    
    @Autowired
    private UserData userData;
    
    userData.getPropertyName();

答案 5 :(得分:3)

您也可以用这种方式来做...。

@Component
@PropertySource("classpath:application.properties")
public class ConfigProperties {

    @Autowired
    private Environment env;

    public String getConfigValue(String configKey){
        return env.getProperty(configKey);
    }
}

然后,无论您要从application.properties中读取什么,只需将密钥传递给getConfigValue方法即可。

@Autowired
ConfigProperties configProp;

// Read server.port from app.prop
String portNumber = configProp.getConfigValue("server.port"); 

答案 6 :(得分:2)

应用程序可以从application.properties文件中读取3种类型的值。

application.properties


     my.name=kelly

my.dbConnection ={connection_srting:'http://localhost:...',username:'benz',password:'pwd'}

课程文件

@Value("${my.name}")
private String name;

@Value("#{${my.dbConnection}}")
private Map<String,String> dbValues;

如果application.properties中没有属性,则可以使用默认值

        @Value("${your_name : default value}")
         private String msg; 

答案 7 :(得分:2)

@Value Spring注解用于将值注入到Spring操纵的bean中的字段中,并且可以应用于字段或构造函数/方法参数级别。

示例

    从注释到字段的
  1. 字符串
    @Value("string value identifire in property file")
    private String stringValue;
  1. 我们还可以使用@Value批注注入 Map 属性。

    首先,我们需要在属性文件中以{key: ‘value' }形式定义属性:

   valuesMap={key1: '1', key2: '2', key3: '3'}

不是说Map中的值必须用单引号引起来。

现在从属性文件中将此值作为Map注入:

   @Value("#{${valuesMap}}")
   private Map<String, Integer> valuesMap;

获取特定键的值

   @Value("#{${valuesMap}.key1}")
   private Integer valuesMapKey1;
  1. 我们还可以使用@Value批注注入 List 属性。
   @Value("#{'${listOfValues}'.split(',')}")
   private List<String> valuesList;

答案 8 :(得分:2)

您可以使用ng-serve批注从application.properties/yml文件中读取值。

@Value

答案 9 :(得分:2)

您可以使用@Value("${property-name}") 如果您的课程带有注释,则为application.properties @Configuration@Component

我尝试的另一种方法是使Utility类以以下方式读取属性-

 protected PropertiesUtility () throws IOException {
    properties = new Properties();
    InputStream inputStream = 
   getClass().getClassLoader().getResourceAsStream("application.properties");
    properties.load(inputStream);
}

您可以使用静态方法来获取作为参数传递的键的值。

答案 10 :(得分:1)

有两种方法,

  1. 您可以在课堂上直接使用@Value
    @Value("#{'${application yml field name}'}")
    public String ymlField;

  1. 要使其干净,您可以清理@Configuration类,在其中可以添加所有@value
@Configuration
public class AppConfig {

    @Value("#{'${application yml field name}'}")
    public String ymlField;
}

答案 11 :(得分:1)

如果您将在一个地方使用此值,则可以使用Try/Catch@Value加载变量,但如果您需要更集中的方式来加载此变量application.properties,更好的方法。

此外,如果您需要不同的数据类型来执行验证和业务逻辑,您可以加载变量并自动投射变量。

@ConfigurationProperties

答案 12 :(得分:1)

尝试过 PropertiesLoaderUtils 类?

这种方法不使用 Spring boot 的注释。传统的 Class 方式。

示例:

Resource resource = new ClassPathResource("/application.properties");
    Properties props = PropertiesLoaderUtils.loadProperties(resource);
    String url_server=props.getProperty("server_url");

使用 getProperty() 方法传递密钥并访问属性文件中的值。

答案 13 :(得分:1)

也许它可以帮助其他人: 你应该从 @Autowired private Environment env;

注入 import org.springframework.core.env.Environment;

然后以这种方式使用它: env.getProperty("yourPropertyNameInApplication.properties")

答案 14 :(得分:0)

1.Injecting a property with the @Value annotation is straightforward:
@Value( "${jdbc.url}" )
private String jdbcUrl;

2. we can obtain the value of a property using the Environment API

@Autowired
private Environment env;
...
dataSource.setUrl(env.getProperty("jdbc.url"));

答案 15 :(得分:0)

最好的方法是使用@Value批注,它将为您的对象private Environment en自动分配值。 这样可以减少代码,并且很容易过滤文件。

答案 16 :(得分:0)

使用最佳方法获取属性值。

1。使用值注释

@Value("${property.key}")
private String propertyKeyVariable;

2。使用环境bean

@Autowired
private Environment env;

public String getValue() {
    return env.getProperty("property.key");
}

public void display(){
  System.out.println("# Value : "+getValue);
}

答案 17 :(得分:0)

我也有这个问题。但是有一个非常简单的解决方案。只需在构造函数中声明您的变量即可。

我的例子:

应用程序属性:

#Session
session.timeout=15

SessionServiceImpl类:

private final int SESSION_TIMEOUT;
private final SessionRepository sessionRepository;

@Autowired
public SessionServiceImpl(@Value("${session.timeout}") int sessionTimeout,
                          SessionRepository sessionRepository) {
    this.SESSION_TIMEOUT = sessionTimeout;
    this.sessionRepository = sessionRepository;
}

答案 18 :(得分:0)

您可以使用@ConfigurationProperties,它很容易访问application.properties中定义的值

#datasource
app.datasource.first.jdbc-url=jdbc:mysql://x.x.x.x:3306/ovtools?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
app.datasource.first.username=
app.datasource.first.password=
app.datasource.first.driver-class-name=com.mysql.cj.jdbc.Driver
server.port=8686
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.database=mysql

@Slf4j
@Configuration
public class DataSourceConfig {
    @Bean(name = "tracenvDb")
    @Primary
    @ConfigurationProperties(prefix = "app.datasource.first")
    public DataSource mysqlDataSourceanomalie() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "JdbcTemplateenv")
    public JdbcTemplate jdbcTemplateanomalie(@Qualifier("tracenvDb") DataSource datasourcetracenv) {
        return new JdbcTemplate(datasourcetracenv);
    }

答案 19 :(得分:0)

对我来说,上述任何一项都对我没有直接作用。 我所做的是:

此外,我在@Rodrigo Villalba Zayas那里回答了
implements InitializingBean上课
并实现了方法

@Override
public void afterPropertiesSet() {
    String path = env.getProperty("userBucket.path");
}

所以看起来像

import org.springframework.core.env.Environment;
public class xyz implements InitializingBean {

    @Autowired
    private Environment env;
    private String path;

    ....

    @Override
    public void afterPropertiesSet() {
        path = env.getProperty("userBucket.path");
    }

    public void method() {
        System.out.println("Path: " + path);
    }
}

答案 20 :(得分:0)

Spring-boot提供了多种方法来提供外部化配置,您可以尝试使用application.yml或yaml文件而不是属性文件,并根据不同的环境提供不同的属性文件设置。

我们可以将每个环境的属性分离到单独的spring配置文件下的单独的yml文件中。然后在部署过程中,您可以使用:

java -jar -Drun.profiles=SpringProfileName

指定要使用的弹簧配置文件。请注意,yml文件的名称应类似于

application-{environmentName}.yml

使它们由springboot自动占用。

参考:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties

要读取application.yml或属性文件:

从属性文件或yml中读取值的最简单的方法是使用spring @value注释。Spring自动将yml中的所有值加载到spring环境中,因此我们可以直接使用来自环境的那些值,例如:

@Component
public class MySampleBean {

@Value("${name}")
private String sampleName;

// ...

}

或者spring提供的另一种读取强类型bean的方法如下:

YML

ymca:
    remote-address: 192.168.1.1
    security:
        username: admin

对应的POJO读取yml:

@ConfigurationProperties("ymca")
public class YmcaProperties {
    private InetAddress remoteAddress;
    private final Security security = new Security();
    public boolean isEnabled() { ... }
    public void setEnabled(boolean enabled) { ... }
    public InetAddress getRemoteAddress() { ... }
    public void setRemoteAddress(InetAddress remoteAddress) { ... }
    public Security getSecurity() { ... }
    public static class Security {
        private String username;
        private String password;
        public String getUsername() { ... }
        public void setUsername(String username) { ... }
        public String getPassword() { ... }
        public void setPassword(String password) { ... }
    }
}

上述方法适用于yml文件。

参考:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

答案 21 :(得分:0)

有两种方法可以从application.properties文件中访问值

  1. 使用@Value批注
    @Value("${property-name}")
    private data_type var_name;
  1. 使用环境类的实例
@Autowired
private Environment environment;

//access this way in the method where it's required

data_type var_name = environment.getProperty("property-name");

您还可以使用构造函数注入或自己创建一个bean来注入环境实例

答案 22 :(得分:0)

为了从属性文件中选择值,我们可以有一个类似于 ApplicationConfigReader.class 的配置读取器类 然后根据属性定义所有变量。参考下面的例子,

application.properties

myapp.nationality: INDIAN
myapp.gender: Male

下面是对应的阅读器类。

@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "myapp") 
class AppConfigReader{
    private String nationality;
    private String gender

    //getter & setter
}

现在我们可以在任何想要访问属性值的地方自动连接阅读器类。 例如

@Service
class ServiceImpl{
    @Autowired
    private AppConfigReader appConfigReader;

    //...
    //fetching values from config reader
    String nationality = appConfigReader.getNationality() ; 
    String gender = appConfigReader.getGender(); 
}

答案 23 :(得分:0)

application.yml 或 application.properties

null

MyConfig 类

config.value1: 10
config.value2: 20
config.str: This is a simle str

任何想要访问配置值的类

@Configuration
@ConfigurationProperties(prefix = "config")
public class MyConfig {
    int value1;
    int value2;
    String str;

    public int getValue1() {
        return value1;
    }

    // Add the rest of getters here...      
    // Values are already mapped in this class. You can access them via getters.
}

答案 24 :(得分:0)

@Value("${userBucket.path}") private String userBucketPath;

答案 25 :(得分:0)

可以使用@Value注解访问spring bean中的属性

@Value("${userBucket.path}")
private String userBucketPath;