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

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

userBucket.path=${HOME}/bucket

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


当前回答

应用程序。Yml或application.properties

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

MyConfig类

@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.
}

任何想要访问配置值的类

@Import(MyConfig.class)
class MyClass {
    private MyConfig myConfig;

    @Autowired
    public MyClass(MyConfig myConfig) {
        this.myConfig = myConfig;
        System.out.println( myConfig.getValue1() );
    }
}

其他回答

另一种方法是将org.springframework.core. environment注入到bean中。

@Autowired
private Environment env;
....

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

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

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

我也有这个问题。但是有一个很简单的解决办法。只需要在构造函数中声明你的变量。

我的例子:

application.propperties:

#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;
}