我想访问应用程序中提供的值。属性,例如:

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

userBucket.path=${HOME}/bucket

我想访问userBucket。在Spring Boot应用程序的主程序中的路径。


当前回答

你可以使用@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);
    }

其他回答

最简单的方法是使用Spring Boot提供的@Value注释。您需要在类级别定义一个变量。例如:

@ value (" $ {userBucket.path} ") private字符串userBucketPath

还有另一种方法可以通过环境类来做到这一点。例如:

自动装配环境变量到你的类,你需要访问这个属性:

@ autowired 私人环境环境

使用环境变量在你需要的行中获取属性值:

environment.getProperty(“userBucket.path”);

希望这能回答你的问题!

遵循以下步骤。 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.
}

您可以使用@Value从应用程序加载变量。如果你在一个地方使用这个值,那么@ConfigurationProperties是一个更好的方法,但是如果你需要一个更集中的方式来加载这些变量。

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

application.properties
custom-app.enable-mocks = false

@Value("${custom-app.enable-mocks}")
private boolean enableMocks;

应用程序可以从应用程序中读取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;

如果你在申请中没有房产。属性,则可以使用默认值

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

可以使用@Value注释从应用程序中读取值。属性/ yml文件。

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