springMVC下自定义配置文件的设置与使用

    xiaoxiao2021-11-22  45

    从来没手动写过这玩意,因部分需求,尝试写了一下,遇到很多问题费了不少时间,在此做个笔记。

    首先是   proName.properties  配置文件 写法很简单 : key = value  例如: myName = jack

    接下来是 configName.xml  文件的配置 

    <?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd" default-autowire="byName"> <!-- beans头部配置 (根据个人需求) --> <context:property-placeholder location="classpath*:config/proName.properties" ignore-unresolvable="true"/> <!-- 说明: 【location】刚才配置的proName.properties 文件路径 【 ignore-unresolvable="true"】 因为项目中已经存在一个:context:property-placeholder (不管是在哪个文件中) 所有的该标签都应加上这句,否则无效 --> <bean id="android" class="com.tek.base.entity.ClassName"> <property name="myName" value="${myName}" /> </bean> <!-- 说明: 【id】随便写 【class】对应的dean文件路径 【name】proName.properties 和 bean对象的参数相对应起来 【value】"${name}" 一样写就是 --> </beans>

    这个写完了,要将configName.xml 文件import进applicationContext.xml去 (本项目中)

    接下来是bean的配置

    @Component("className") //这里使用的是Component注解,还有多种其他方法 public class ClassName{private String myName;public String getMyName() {return myName;}public void setMyName(String myName) {this.myName = myName;}}

    用@Component进行注解后在controller中进行使用:

    @RequestMapping("/getVersion") @ResponseBody public ReMobileVo getVersion() { ApplicationContext context = new FileSystemXmlApplicationContext("../webapps/ssms/WEB-INF/classes/spring/configName.xml"); //这里使用的是绝对路径,还有多种其他方法   ClassName className = (ClassName)context.getBean("className"); String name= className.getMyName(); System.out.println(name); } 至此完成。

    转载请注明原文地址: https://ju.6miu.com/read-678455.html

    最新回复(0)