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

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

userBucket.path=${HOME}/bucket

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


当前回答

另一种在配置中找到键/值的方法。

...
import org.springframework.core.env.ConfigurableEnvironment;
...
@SpringBootApplication
public class MyApplication {

    @Autowired
    private ConfigurableEnvironment  myEnv;

...
  
    @EventListener(ApplicationReadyEvent.class)
    public void doSomethingAfterStartup() 
    throws Exception {
        
        LOG.info("myEnv (userBucket.path): " + myEnv.getProperty("userBucket.path"));
    }
} 

其他回答

应用程序。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() );
    }
}

属性中的@Value("${property-name}") 应用程序。属性 @配置或@组件。

我尝试的另一种方法是用下面的方式创建一个Utility类来读取属性

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

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

实际上有三种方法来读取应用程序。属性文件,

使用环境,

@Autowired
Environment environment

environment.getProperty({propertyName})

或者使用@Value,

@Value("${property}")

但是@Value的问题是,如果值不在属性文件中,它可能会抛出异常

建议使用@ConfigurationProperties

@ConfigurationProperties("userBucket")
public class test{
  private String path;
  //getters and setters
}

详细示例-读取application.properties

另一种在配置中找到键/值的方法。

...
import org.springframework.core.env.ConfigurableEnvironment;
...
@SpringBootApplication
public class MyApplication {

    @Autowired
    private ConfigurableEnvironment  myEnv;

...
  
    @EventListener(ApplicationReadyEvent.class)
    public void doSomethingAfterStartup() 
    throws Exception {
        
        LOG.info("myEnv (userBucket.path): " + myEnv.getProperty("userBucket.path"));
    }
} 
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"));