Comparison of SpringBoot 2 @Value and @ConfigurationProperties to obtain the attribute value of the configuration file

The content of the application.yml file is as follows

person:
  name: zhangshan
  age: 18
  hobby: [篮球,羽毛球]

The test class yamlTest is as follows

import com.douya.example.model.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class yamlTest {
    @Autowired
    Person person;

    @RequestMapping("/person")
    public Person hello(){
        return person;
    }
}

Use the @ConfigurationProperties annotation to map the information in the configuration file to the Person class as follows:

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix="person")#prefix中的值必须为小写
public class Person {
    private String name;
    private Integer age;
    private String[] hobby;
}

The postman access results are as follows

When using the @Value annotation to map the information of the configuration file to the Person class, the code and error are as follows

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Data
@Component
public class Person {
    @Value("${person.name}")
    private String name;
    @Value("${person.age}")
    private Integer age;
    @Value("${person.hobby}")
    private String[] hobby;
}

The error is as follows:

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'yamlTest': Unsatisfied dependency expressed through field 'person'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'person': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'person.hobby' in value "${person.hobby}"

After checking, it is known that @Value does not support complex type encapsulation, so the value injection of hobby of type string[] fails.

The difference between the @Value annotation and @ConfigurationProperties is attached below

reference:

springboot --- Configure the difference between @ConfigurationPropeties and @value_NDSoumig's Blog-CSDN Blog

 

 Note: The rookie's first blog records the problems encountered in the learning process. If the writing is not good, please point it out, thank you

 

 

Guess you like

Origin blog.csdn.net/qq_45064423/article/details/121647798