1. 程式人生 > >javaEE Springmvc,properties檔案解決硬編碼問題,@Value註解獲取properties檔案中的內容

javaEE Springmvc,properties檔案解決硬編碼問題,@Value註解獲取properties檔案中的內容

springmvc.xml(Springmvc的核心配置檔案,讀取properties檔案):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
	
	<!-- 配置@Controller掃描 -->
	<context:component-scan base-package="com.xxx.crm.controller" />
	
	<!-- 讀取.properties檔案中的內容。 通過${鍵}的方式可以獲取properties中對應的值。 -->
	<context:property-placeholder location="classpath:resource.properties" />
	
	<!-- 配置註解驅動; 指定處理器對映器、處理器介面卡; -->
	<mvc:annotation-driven />
	
	<!-- 配置檢視解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 字首 -->
		<property name="prefix" value="/WEB-INF/jsp/" />
		<!-- 字尾 -->
		<property name="suffix" value=".jsp" />
	</bean>
	
</beans>
	

CustomerController.java(Controller後端控制器,@Value註解獲取properties檔案中的內容):

package com.xxx.crm.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xxx.crm.pojo.BaseDict;
import com.xxx.crm.pojo.QueryVo;
import com.xxx.crm.service.BaseDictService;

//客戶管理
@Controller
public class CustomerController {

	@Autowired
	private BaseDictService baseDictService;
	
	//註解在成員變數上
	//通過@Value註解,將springmvc.xml檔案中載入的xxx.properties中的內容賦給成員變數。
	@Value("${fromType.code}")
	private String fromTypeCode;
	
	
	@RequestMapping(value = "/customer/list")
	public String list(QueryVo vo,Model model){
		List<BaseDict> fromType = baseDictService.selectBaseDictListByCode(fromTypeCode);
		model.addAttribute("fromType", fromType);
		//..................
		return "customer";
	}
	
}

resource.properties(properties檔案):

fromType.code=002