Spring MVC 通过 @PropertySource和@Value 来读取配置文件
在这篇文章中,我们会利用Spring的@PropertySource和@Value两个注解从配置文件properties中读取值。先来段java代码:

@Component
@PropertySource(value = {"classpath:common.properties", "classpath:abc.properties"})
public class Configs {
@Value("${connect.api.apiKeyId}")
public String apiKeyId;
@Value("${connect.api.secretApiKey}")
public String secretApiKey;
public String getApiKeyId() {
return apiKeyId;
}
public String getSecretApiKey() {
return secretApiKey;
}
}

我们来具体分析下:
1、@Component注解说明这是一个普通的bean,在Component Scanning时会被扫描到并被注入到Bean容器中;我们可以在其它引用此类的地方进行自动装配。@Autowired这个注解表示对这个bean进行自动装配。 比如:

@Controller
public class HomeController {
@Autowired
private Configs configs;
}

2、@PropertySource注解用来指定要读取的配置文件的路径从而读取这些配置文件,可以同时指定多个配置文件;
3、@Value("${connect.api.apiKeyId}")用来读取属性key=connect.api.apiKeyId所对应的值并把值赋值给属性apiKeyId;
4、通过提供的get方法来获取属性值,如:

@Controller
public class HomeController {
@Autowired
private Configs configs;
private void decrytCardInfo(AtomRequest req) throws Exception {
req.setCardNo(ChipherUtils.desDecrypt(ChipherUtils.decodeBase64(req.getCardNo()), configs.getCardKey(), Consts.CHARSET_UTF8));
}
}

总结:
@Component+@PropertySource+@Value==强大+便捷+高效
标签: Java, Spring MVC
本文介绍如何使用SpringMVC中的@PropertySource和@Value注解从properties配置文件读取值,通过示例代码详细解析了配置过程及应用。
2965

被折叠的 条评论
为什么被折叠?



