Tocchetto
Tocchetto

Reputation: 176

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

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

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. 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.

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

Upvotes: 2

Views: 5192

Answers (1)

Mark Thomas
Mark Thomas

Reputation: 54

My only guess would be that the @Value annotation inside your SubListener class is from the wrong package. 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.

Upvotes: 3

Related Questions