85-002-19 SSH项目中利用spring的SpEL表达式语言来注入文件在项目中绝对路径

来源:互联网 发布:淘宝秋季女装 编辑:程序博客网 时间:2024/06/07 18:53

图文版:http://note.youdao.com/yws/public/redirect/share?id=abc20790e48da5130e227d9390e4df92&type=false
资源文件下载 https://yunpan.cn/OcRaTMHR3NWIIf  访问密码 4b2c


 19.1 现在处理图片上传的绝对路径(此路径会保存到数据库中),先建立一个图片存放的文件夹   

19.2 为了后期维护定义一个资源文件来指定图片的上传路径

        public.properties

19.3 创建资源文件后,那么就需要加载这个资源文件,通过spring来处理
        applicationContext-public.xml
<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean" >
        <property name="locations">
            <array>
                <value>classpath:public.properties</value>
            </array>
        </property>
    </bean>
    然后在文件上传工具类中通过spring的spel表达式语言来注入此资源文件的路径值
    FileUploadUtil.java
private String filePath = "H:/";  //初始化一个文件上传路径
    @Value("#{prop.filePath}") //通过spring的spel语言从资源文件中读取路径值再注入到变量中
    //一定要有setter方法,否则spring无法通过反射调用来实现注入
   public void setFilePath(String filePath) {
        //System.out.println(filePath) ;
        this.filePath = filePath;
    }
19.4 顺便把数据库链接的参数也通过资源文件配置(配置的资源文件一般放到工程根目录下)

    conn.properties

dataSource=com.mchange.v2.c3p0.ComboPooledDataSource
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/shop
user=zz
password=123456

    同时在定义spring的配置文件

    applicationContext-public.xml

<!-- spring管理加载资源文件 -->
    <context:property-placeholder location="classpath:conn.properties"/>
    <bean id="dataSource" class="${dataSource}">
        <property name="driverClass" value="${driverClass}"/>
        <property name="jdbcUrl" value="${jdbcUrl}" />
        <property name="user" value="${user}" />
        <property name="password" value="${password}" />
    </bean>

19.5 通过上面两个资源文件的配置,以后项目转移到其他地方时,只要修改资源文件变量即可,无需对工程代码动手术。


0 0
原创粉丝点击