Spring Boot @Value属性 [英] Spring Boot @Value Properties

查看:225
本文介绍了Spring Boot @Value属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Spring Boot应用程序,在其中一个类中,我尝试使用@Value从application.properties文件中引用一个属性.但是,该属性未解决.我看过类似的帖子,并尝试按照建议进行操作,但这无济于事.该类是:

I have a Spring Boot application and in one of the classes, I try to reference a property from the application.properties file using @Value. But, the property does not get resolved. I have looked at similar posts and tried following the suggestions, but that didn't help. The class is:

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class PrintProperty {

  @Value("${file.directory}")
  private String fileDirectory;

  public void print() {
    System.out.println(fileDirectory);
  }
}

我在application.properties中具有属性file.directory.我也有其他领域.

I have the property file.directory in application.properties. I have other fields as well.

推荐答案

我遇到了与您相同的问题.这是我的错误代码.

I had the same problem like you. Here's my error code.

@Component
public class GetExprsAndEnvId {
    @Value("hello")
    private String Mysecret;


    public GetExprsAndEnvId() {
        System.out.println("construct");
    }


    public void print(){
        System.out.println(this.Mysecret);
    }


    public String getMysecret() {
        return Mysecret;
    }

    public void setMysecret(String mysecret) {
        Mysecret = mysecret;
    }
}

这没问题,但是 我们需要像这样使用它:

This is no problem like this, but we need to use it like this:

@Autowired
private GetExprsAndEnvId getExprsAndEnvId;

不是这样的:

getExprsAndEnvId = new GetExprsAndEnvId();

在这里,用@Value注释的字段为null,因为Spring不知道用new创建的GetExprsAndEnvId的副本,也不知道如何在其中注入值.

Here, the field annotated with @Value is null because Spring doesn't know about the copy of GetExprsAndEnvId that is created with new and didn't know to how to inject values in it.

这篇关于Spring Boot @Value属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆