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

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

userBucket.path=${HOME}/bucket

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


当前回答

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

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

OR

要使它干净,你可以清除@Configuration类,在那里你可以添加所有的@value

@Configuration
public class AppConfig {

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

获取财产价值的最佳方法是使用。

1. 使用Value注释

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

从应用程序中获取价值有两种方法。属性文件

使用@Value注释

    @Value("${property-name}")
    private data_type var_name;

使用环境类的实例

@Autowired
private Environment environment;

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

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

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

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

您可以使用@Value注释并访问您所使用的Spring bean中的属性

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

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