Home > Software engineering >  spring @value annotation returns null with non static variable
spring @value annotation returns null with non static variable

Time:09-30

I need to read the value from my application.properties file and I've tried this:

@ComponentScan(basePackages = "myservice")
public class MailServiceAuthProvider {
    @Value("${my.name}")
    private String name;

    public void myMethod()
    {
      System.out.println(name);
    }
}

my application.properties in the resource folder of the same package :

my.name=name

but this is always null

I've even tried not to read from the properties file but directly give the value @Value("default-name") in the annotation, but it is also null.

I've read some tutorials and some posts there and they're using the same configuration. What am I doing wrong?

UPD I've instantiated MailServiceAuthProvider as following:

@SpringBootApplication
public class App() implements CommandLineRunner {
    @Autowired
    MailServiceAuthProvider a;

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

    @Override
    public void run(String... args) throws Exception {
        a.myMethod();
    }
}

CodePudding user response:

Use @Component instead of @ComponentScan(basePackages = "myservice") so that you can make MailServiceAuthProvider a Spring-managed Bean:

@Component
public class MailServiceAuthProvider {
    @Value("${my.name}")
    private String name;

    public void myMethod()
    {
      System.out.println(name);
    }
}

Assuming you have something like the following main class in the base package of your application, you don't even need @ComponentScan annotation.

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

Why? Because @SpringBootApplication encapsulates @Configuration, @EnableAutoConfiguration, and @ComponentScan annotations with their default attributes. The default value for @ComponentScan means that all the sub-packages on the package the @ComponentScan is used are scanned. That is why it is usually a good practice to include the main class in the base package of the project.

CodePudding user response:

Okay, I've finally solved the issue. The problem was that I instantiated MailServiceAuthProvider with keyword new:

MailServiceAuthProvider instance = new MailServiceAuthProvider();
instance.myMethod();

, but instead, I should use @Autowired like that:

@Autowired
MailServiceAuthProvider instance;

//...some code
instance.myMethod();

Hope it will be helpful for someone

  • Related