In this article, we will use the spring @propertysource and @value two annotations to read the values from the configuration file properties. First, a snippet of Java code:
@Component @propertysource (value= {"Classpath:common.properties", "Classpath:abc.properties"}) Public classconfigs {@Value ("${connect.api.apikeyid}") PublicString Apikeyid; @Value ("${connect.api.secretapikey}") PublicString Secretapikey; PublicString Getapikeyid () {returnApikeyid; } PublicString Getsecretapikey () {returnSecretapikey; }}
Let us specifically analyze:
1, @Component Note that this is an ordinary bean, component scanning will be scanned and injected into the bean container; We can automate the assembly in other places that reference this type. @Autowired This annotation indicates that the bean is automatically assembled. Like what:
@Controller Public class HomeController { @Autowired private configs configs;}
2, @PropertySource annotations are used to specify the path of the configuration file to read to read these configuration files, you can specify more than one configuration file;
3, @Value ("${connect.api.apikeyid}") is used to read the value of the property Key=connect.api.apikeyid and assigns the value to the property apikeyid;
4. Obtain the property value by providing a Get method, such as:
@Controller Public class HomeController { @Autowired private configs configs; Private void throws Exception { configs.getcardkey (), Consts.charset_utf8));} }
Summarize:
@[email protected][email protected]== Powerful + convenient + efficient
Spring MVC reads configuration files through @PropertySource and @value