首页 > 编程语言 > 详细

Spring MVC 通过 @PropertySource和@Value 来读取配置文件

时间:2017-05-22 16:02:54      阅读:420      评论:0      收藏:0      [点我收藏+]

在这篇文章中,我们会利用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==强大+便捷+高效

Spring MVC 通过 @PropertySource和@Value 来读取配置文件

原文:http://www.cnblogs.com/frankyou/p/6889605.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!