【问题标题】:@Value from application.properties in SpringBoot gives null all the timeSpringBoot 中 application.properties 中的 @Value 始终为 null
【发布时间】:2019-01-06 19:11:21
【问题描述】:

如何正确地从 application.properties 文件中注入值?

主类:

@SpringBootApplication
public class Main {


    public static void main(String args[]) {
        SpringApplication.run(Main.class,args);
    }

application.properties 文件:

my.password=admin

测试类:

@Component
public class Test {
    @Value("${my.password}")
    private String mypassword;

    public String getMypassword() {
        return mypassword;
    }

    public void setMypassword(String mypassword) {
        this.mypassword = mypassword;
    }

    public Test(){
        System.out.println("@@@@@@@@@@@@@@@@@@@"+ mypassword);
    }
}

控制台打印始终为 null,而不是来自 application 文件的值

【问题讨论】:

  • 我不认为 Value 标记在调用构造函数之前分配了值。我可能是错的,但是在新函数上使用 PostConstruct 标记并打印值,看看是否有效。
  • 你是对的,谢谢你的帮助

标签: java spring-boot properties components


【解决方案1】:

在创建类时(即调用构造函数时)不会注入属性,而是稍后注入。因此,您会在构造函数中看到 null。

尝试像这样添加带有@PostConstruct 注释的方法并检查结果:

@PostConstruct
public void afterCreation(){
    System.out.println("@@@@@@@@@@@@@@@@@@@"+ mypassword);
}

【讨论】:

  • 谢谢,你是对的。但我还有另一个问题。它适用于@PostConstruct,但是当我尝试创建 Test t = new Test();并调用 afterCreation() 它再次打印 null 。有没有另一种在springboot中创建对象的方法?因为我也试过 "@"Autowired Test t;然后调用 foobar() 但我得到空指针异常
  • 当你做新的,那么你正在创建一个新的对象。而不是春豆。因此@value 或任何弹簧注释没有任何意义,因此为空。在春季环境中做new 是一种犯罪:)
  • 谢谢,但是我应该如何创建对象呢?我想我可以在我的“@”组件上调用@Autowired。但我只剩下空指针了。
  • 你能发布一个你描述的例子吗?如果您的类是 bean(具有这些注释之一 @component、@service、...),那么自动装配不应为 null,前提是您使用的类 @autowired 也是 bean。
  • 我会尽快将其发布在答案中,但问题可能出在@bean 部分,因为我只是使用“@”Component
【解决方案2】:

@pvpkiran 我正在尝试将其添加到我的主要方法中,其余部分保持不变。

@SpringBootApplication
public class Application {
    @Autowired
    static Test  t;
    public static void main(String args[]){
        SpringApplication.run(Application.class,args);

        t.foobar();
    }
}

【讨论】:

  • 我意识到我现在可能正在做一些春天的异端邪说,但是有人能这么好心地给我展示一个使用@Autowired 创建对象并在代码中某处调用其方法的示例吗?我在任何地方都找不到它。
猜你喜欢
  • 2018-02-12
  • 2018-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-15
  • 2020-11-09
  • 1970-01-01
相关资源
最近更新 更多