Home > Software engineering >  Spring Boot @ConfigurationProperties
Spring Boot @ConfigurationProperties

Time:11-01

so I'm kinda new to Springboot and I'm trying to get the value from application.properties. I want to get multiple value from the application.properties and insert it into a list. At first, I tried to get the value from controller class and it works. Now I tried to get the value from a new class, but the value won't show up and it's showing an error because it says that it's null. Am i missing an annotation or did i do something wrong in the code? Below is my code.

application.properties:

example.name[0] = asdf
example.name[1] = qwer

List Value class:

@ConfigurationProperties(prefix = "example")
@Configuration
public class NameProperties {

    private List<String> name;
    
    public List<String> getName() {
        return name;
    }
    public void setName(List<String> name) {
        this.name = name;
    }

}

What i tried in controller and worked:

@RestController
@CrossOrigin
@RequestMapping("/tes/**")
public class NameController {

    @Autowired
    NameProperties property = new NameProperties();
    
    @GetMapping
    public String tes() {
        String name = property.getName().get(0);

        System.out.println(name);
        return name;
    }
}

In the new class that doesn't work:

@Component
public class NameConfiguration {

    @Autowired
    NameProperties property = new NameProperties();
    
    public void getName(int index) {
        System.out.println(property.getName().get(0));
    }
    
}

The code to test the new class in the controller:

@RestController
@CrossOrigin
@RequestMapping("/tes/**")
public class NameController {

    NameConfiguration conf = new NameConfiguration();
    
    @GetMapping
    public String tes() {
        conf.getName(0);
    }
}

Is it because the value doesn't get injected when I call the class or what should I do? Appreciate any kind of help. Thanks!

CodePudding user response:

Hello friend when you declare your class as a Spring Bean you shouldn't initialize the object yourself other the properties define in it will not be injected by Spring, so you should let spring help you with that, try these class below

NameProperties

@Component
@ConfigurationProperties(prefix = "example")
public class NameProperties {

    private List<String> name;
    
    public List<String> getName() {
        return name;
    }
    public void setName(List<String> name) {
        this.name = name;
    }

}

NameConfiguration.java

@Component
public class NameConfiguration {

    @Autowired
    NameProperties property;
    
    public void getName(int index) {
        System.out.println(property.getName().get(0));
    }
    
}
  • Related