IDEA社区版搭建Spring工程(04-加载配置文件及加解密)

Andy_lu020 / 2024-07-10 / 原文

Spring MVC 加载配置文件的几种方式

  1. 通过 context:property-placeholde 实现加载配置文件

在 springmvc.xml 配置文件里加入 context 相关引用

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
 xmlns:context="http://www.springframework.org/schema/context"  
 xsi:schemaLocation="http://www.springframework.org/schema/beans  
      http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd">

引入config配置文件 <context:property-placeholder location="classpath:config.properties"/>

  • 通过context:property-placeholde加载多个配置文件,只需将多个配置文件以逗号分隔即可。

config配置文件内容如下:

hello.content=hello,everyone.

在Java类中调用

@Value("${hello.content}")
private String content;
  1. 通过util:properties实现配置文件加载

在springmvc.xml中加入util相关引用

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
 xmlns:context="http://www.springframework.org/schema/context"  
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 xmlns:util="http://www.springframework.org/schema/util"  
 xsi:schemaLocation="http://www.springframework.org/schema/beans  
      http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
      http://www.springframework.org/schema/context  
      http://www.springframework.org/schema/context/spring-context.xsd  
      http://www.springframework.org/schema/util  
      http://www.springframework.org/schema/util/spring-util-4.0.xsd"> 

引入config配置文件 <util:properties id="settings" location="classpath:config.properties"/>

在Java类中调用

@Value("#{settings['hello.content']}")
private String content;
  1. 直接在Java类中通过注解实现配置文件加载

在java类中引入配置文件

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration  
@PropertySource(value="classpath:config.properties")    
public class Config {

@Value("${hello.content}")
public  String content;

}

在springmvc配置文件里添加

<context:component-scan base-package="springmvc"/>

<!-- 配置springMVC开启注解支持 -->
<mvc:annotation-driven/>

在controller中调用

@Autowired  
private Config Config; //引用统一的参数配置类  

@RequestMapping(value={"/hello"})  
public ModelMap test(ModelMap modelMap) {   
  modelMap.put("message", Config.content);  
      return modelMap;