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==强大+便捷+高效

原文地址:https://www.cnblogs.com/frankyou/p/6889605.html