Spring boot 实用又冷门的注解

一、注解

这一期先做注解的统计,遇到了我就在文章末尾append

 1.@ConfigurationProperties("xxx")

 通常我们使用@Value()注解注入配置文件中的参数,但是当配置参数非常复杂,层级很深时就显得很臃肿,这个时候这个注解就派上用场了,例如我们配置文件:

acme.enabled=false;
acme.remote-address=192.168.1.10;
acme.security.username=BBSee;
acme.security.password=123*_678;
acme.security.roles=管理员;

我们就可以用下面的方式注入: 

package com.example;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties("acme")
public class AcmeProperties {

	private boolean enabled;

	private InetAddress remoteAddress;

	private final Security security = new Security();

	public boolean isEnabled() { ... }

	public void setEnabled(boolean enabled) { ... }

	public InetAddress getRemoteAddress() { ... }

	public void setRemoteAddress(InetAddress remoteAddress) { ... }

	public Security getSecurity() { ... }

	public static class Security {

		private String username;

		private String password;

		private List roles = new ArrayList<>(Collections.singleton("USER"));

		public String getUsername() { ... }

		public void setUsername(String username) { ... }

		public String getPassword() { ... }

		public void setPassword(String password) { ... }

		public List getRoles() { ... }

		public void setRoles(List roles) { ... }

	}
}

 yml:

my:
servers:
	- dev.bbsee.com
	- another.bbsee.com
@ConfigurationProperties(prefix="my")
public class Config {

	private List servers = new ArrayList();

	public List getServers() {
		return this.servers;
	}
}

然后,你就可以当做bean来使用了:

@Service
public class MyService {

	private final AcmeProperties properties;

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

 	//...

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

}

该注解下还有诸多功能,如:配置格式转换、参数有效性校验等

你可能感兴趣的:(Java,Spring)