0

I'm new to Java/Spring and tried to read properties from a file. This is what I did so far.

Controller.java launches the application:

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;

@EnableAutoConfiguration
public class Controller {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Controller.class, args);
        Test test = new Test();
        test.doWork();
    }

}

This calls the doWork() method of Test.java:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.PropertySource;

@EnableAutoConfiguration
@PropertySource("application.properties")
public class Test {

    @Value("${db.password}")
    private String dbPassword;

    public void doWork() {
        System.out.println(dbPassword);
    }

}

I put some properties in application.properties:

db.password=Snap&Fudge!

The file structure of the project looks like this:

./pom.xml
./src/main/java/Controller.java
./src/main/java/Test.java
./src/main/resources/application.properties

When I run the application, I see that Test.doWork() is run, but instead of printing out the property, it returns null.

Can you see what I'm doing wrong?

Alex Woolford
  • 4,433
  • 11
  • 47
  • 80

1 Answers1

2

You are creating a new instance of test yourself instead of using a spring managed instance.

First change your Controller class.

@SpringBootApplication
public class Controller {
    public static void main(String[] args) throws Exception {
        ApplicationContext ctx = SpringApplication.run(Controller.class, args);
        Test test = ctx.getBean(Test.class);
        test.doWork();
    }
}

Next change your Test class.

@Component 
public class Test {

    @Value("${db.password}")
    private String dbPassword;

    public void doWork() {
        System.out.println(dbPassword);
    }

}

Now you will have a Spring managed (and configured) instance of the Test class, which you get from the ApplicationContext.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224