8 -- 深入使用Spring -- 3...3 使用Resouce作为属性

本文介绍如何在Spring框架中使用依赖注入的方式为Bean实例提供Resource资源访问能力,避免硬编码资源路径,实现更灵活的资源定位。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      8.3.3 使用Resouce作为属性

        当应用程序中的Bean实例需要访问资源时,Spring可以直接利用依赖注入。

        如果Bean实例需要访问资源,有如下两种解决方案:

          ⊙ 在代码中获取Resource实例。

          ⊙ 使用依赖注入。

        在代码中获取Resource实例:当程序获取Resource实例时,总需要提供Resource所在的位置,不管通过FileSystemResource创建实例,还是通过ClassPathResource创建实例,或者通过ApplicationContext的getResource()方法获取实例,都需要提供资源位置。这意味着:资源所在的物理位置将被耦合到代码中,如果资源位置放生改变,则必须改写程序。

        使用依赖注入:让Spring为Bean实例依赖注入资源。

        Class : TestBean

package edu.pri.lime._8_3_3.bean.impl;

import org.springframework.core.io.Resource;

public class TestBean {

    private Resource res;

    public void setRes(Resource res) {
        this.res = res;
    }
    public void parse(){
        System.out.println(res.getFilename());
        System.out.println(res.getDescription());
    }
    public Resource getRes() {
        return res;
    }
    
}

        XML : 

<?xml version="1.0" encoding="UTF-8"?>
<!-- Spring 配置文件的根元素,使用Spring-beans-4.0.xsd语义约束 -->
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:P="http://www.springframework.org/schema/p"
    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">

    <bean id="testBean" class="edu.pri.lime._8_3_3.bean.impl.TestBean" >
        <!-- 可以使用file:、http:、ftp:等前缀强制Spring采用对应的资源访问策略 -->
        <!-- 如果不采用任何前缀,则Spring将采用与该ApplicationContext相同的资源访问策略来访问资源 -->
        <property name="res" value="classpath:book.xml"/>
    </bean>

</beans>

        Class : SpringTest

package edu.pri.lime._8_3_3.bean.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import edu.pri.lime._8_3_3.bean.impl.TestBean;

public class SpringTest {

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("app_8_3_3.xml");
        TestBean testBean = ctx.getBean("testBean",TestBean.class);
        testBean.parse();
    }
}

        采用依赖注入,允许动态配置资源文件位置,无须将资源文件位置写在代码中,当资源文件位置发生变化时,无须改写程序,直接修改配置未见即可。

啦啦啦

啦啦啦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值