怎么在代码中去读取 上面的属性
时间: 2024-04-10 18:33:26 浏览: 15
要在代码中读取上面的属性,你可以使用 Spring 的 Environment 对象来获取属性值。以下是一个示例代码:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
@PropertySource("classpath:test.properties")
public class MyComponent {
@Autowired
private Environment env;
@Value("${my.property}")
private String myProperty;
public void printProperty() {
String propertyValue = env.getProperty("my.property");
System.out.println("My property value from env is: " + propertyValue);
System.out.println("My property value from @Value is: " + myProperty);
}
}
```
在上面的代码中,我们通过 `@Autowired` 注解将 `Environment` 对象注入到 `env` 字段中。然后,我们可以使用 `getProperty()` 方法从 `Environment` 对象中获取属性值。
另外,我们还可以使用 `@Value` 注解将属性值直接注入到 `myProperty` 字段中,并直接使用它。
在这个例子中,假设我们的属性文件 `test.properties` 中有以下内容:
```properties
my.property=Hello, World!
```
当调用 `printProperty()` 方法时,将会输出以下内容:
```
My property value from env is: Hello, World!
My property value from @Value is: Hello, World!
```
这样我们就可以使用 `Environment` 对象或 `@Value` 注解来读取属性值。