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

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

userBucket.path=${HOME}/bucket

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


当前回答

也许它可以帮助其他人: 你应该注入@Autowired私有环境env;from import org.springframework.core. environment;

然后这样使用它: env.getProperty(“yourPropertyNameInApplication.properties”)

其他回答

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

}

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

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

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

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

@ autowired 私人环境环境

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

environment.getProperty(“userBucket.path”);

希望这能回答你的问题!

最好的方法是使用@Value注释,它会自动为你的对象私有环境赋值。 这将减少你的代码,它将很容易过滤你的文件。

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

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

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

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