Because I have always been ignorant of these similar annotations, I often feel that it must be the author’s fault no matter what the fault is. So recently spent some time to study the specific use method, to avoid mistakes in the future. I often read articles on CSDN when I used them before. They were copied from each other in the same way, and no one corrected whether they were right or not. So I wrote down my feelings.

The main purpose of the @Configuration annotation is to use the class using the annotation as a Bean to configure the Spring container. ConfigurationProperties(prefix=” XXXX “) is used to obtain the values of elements with the same parent tag. See below for specific use cases. * * @ EnableConfigurationProperties (XXX. Class) * * will be configured class, class, fill in the parameter.

Specific cases:

my:
servers:
	- dev.example.com
	- another.example.com
Copy the code

If we want to get the configuration parameters of the YML file, we can do so in this way

@ConfigurationProperties(prefix="my")
public class Config {

	private List<String> servers = new ArrayList<String>();

	public List<String> getServers(a) {
		return this.servers; }}Copy the code

Use this annotation in a class to get the properties, and the class needs getter and setter methods. This is equivalent to the ability to retrieve parameter attributes in yML files, but does not mean that you can use them. You need to add the @Component annotation to the class so that Spring can retrieve the relevant attributes.

@Component
@ConfigurationProperties(prefix="acme")
public class AcmeProperties {

	// ... see the preceding example

}
Copy the code

Another method is to use the Configuration class class above marked * * @ Configuration and @ EnableConfigurationProperties (XXX. Class) * *

@Configuration
@EnableConfigurationProperties(XXXProperties.class)
public class MyConfiguration {}Copy the code
# application.yml
acme:
	remote-address: 192.1681.1.
	security:
	    username: admin
	    roles:
	        - USER
	        - ADMIN
Copy the code
@Service
public class MyService {

	private final AcmeProperties properties;

	@Autowired
	public MyService(AcmeProperties properties) {
	    this.properties = properties;
	}

 	/ /...

	@PostConstruct
	public void openConnection(a) {
		Server server = new Server(this.properties.getRemoteAddress());
		// ...}}Copy the code

This method can also be used to read the corresponding configuration from a YAML file and then use the @service layer as a constructor for things like this to call the related properties. Personal writing is very bad, please point out the specific problem in the comments.