简体   繁体   English

Spring Boot @Value为空

[英]Spring boot @Value is null

Before we start, yes I know there's another question out there but they are not the same issue and I couldn't find anything to solve this. 在开始之前,是的,我知道那里还有另一个问题,但是它们不是同一个问题,我找不到任何解决方法。

Ok, I have 好吧,我有

package a
imports ...
@SpringBootApplication
public class LauncherApplication implements CommandLineRunner {

  @Autowired
  private SubListener subListener;

  @Value("${proj.id}")
  private String testy;

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

}


@Override
public void run(String... args) throws Exception {
    System.out.println(subListener.getProjID());
    System.out.println(testy);
  }
}

Then on my subListener 然后在我的subListener上

package a.b
imports ...
@Component
public class SubListener {

  @Value("${proj.id}")
  private String projID;

  public String getProjID() {
    return projID;
  }
}

and finally inside my resources folder on application.properties 最后在application.properties的资源文件夹中

proj.id=Hello from file

Now, by all accounts this should work, the SpringBootApplication has the component scan thing, the bean is marked as @component and is a subpackage of the springbootapplication, the properties file has the default name and in the default directory. 现在,从所有方面来看,这应该起作用,SpringBootApplication拥有组件扫描功能,bean被标记为@component,并且是springbootapplication的子包,属性文件具有默认名称和默认目录。 I can't find a single reason for this not to work. 我找不到导致此失败的单一原因。 Also mind you that when I call the property on testy it works, it only return null when it's returning from the sublistener. 还请注意,当我在testy上调用该属性时,该属性有效,但从子侦听器返回时,它仅返回null。

Thank you for your time 感谢您的时间

EDIT: 编辑:

New launcherApplication 新启动器应用

@SpringBootApplication
public class LauncherApplication {

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

    }

    @Bean
  public CommandLineRunner runner(SubListener subListener){
      CommandLineRunner runner = new CommandLineRunner() {
      @Override
      public void run(String... args) throws Exception {
        System.out.println(subListener.getProjID());
      }
    };
    return runner;
  }
}

It still returns null though 虽然它仍然返回null

My only guess would be that the @Value annotation inside your SubListener class is from the wrong package. 我唯一的猜测是SubListener类中的@Value注释来自错误的程序包。 Can you please check that you are using this import and not something else: 您能否检查您正在使用此导入,而不要使用其他导入:

import org.springframework.beans.factory.annotation.Value;

I've copied your code and it's working for me. 我已经复制了您的代码,并且对我有用。 If you still can't get it working then I'd recommend trying to reproduce it in a new empty project. 如果您仍然无法使用它,那么我建议您尝试在一个新的空项目中重现它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM