[转]Spring Resource loader with GetResource() example

本文深入探讨了Spring的资源加载器功能,通过示例展示了如何使用getResource()方法从文件系统、URL路径和类路径加载资源。此外,文章还介绍了如何在bean中访问资源,并提供了配置和实现细节。

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

转载地址:http://www.mkyong.com/spring/spring-resource-loader-with-getresource-example/

Spring’s resource loader provides a very generic getResource() method to get the resources like (text file, media file, image file…) from file system , classpath or URL. You can get the getResource() method from the application context.

Here’s an example to show how to use getResource() to load a text file from

1. File system

Resource resource = appContext.getResource("file:c:\\testing.txt");

2. URL path

Resource resource = appContext.getResource("url:http://www.yourdomain.com/testing.txt");

3. Class path

Resource resource = appContext.getResource("classpath:com/mkyong/common/testing.txt");

You just need to specify the resource location, and the Spring will handle the rest and return you a Resource object.

Full example withgetResource() method.

package com.mkyong.common;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
public class App 
{
    public static void main( String[] args )
    {
    	ApplicationContext appContext = 
    	   new ClassPathXmlApplicationContext(new String[] {"If-you-have-any.xml"});
 
    	Resource resource = 
           appContext.getResource("classpath:com/mkyong/common/testing.txt");
 
    try{
     	  InputStream is = resource.getInputStream();
          BufferedReader br = new BufferedReader(new InputStreamReader(is));
 
          String line;
          while ((line = br.readLine()) != null) {
             System.out.println(line);
       	  } 
          br.close();
 
    	}catch(IOException e){
    		e.printStackTrace();
    	}
 
    }
}

Bean resource loader (ResourceLoaderAware)

Since bean does not have the application context access, how can a bean access a resources? The workaround is implement the ResourceLoaderAware interface and create setter method for ResourceLoader object. Spring will DI the resource loader into your bean.

package com.mkyong.customer.services;
 
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
 
public class CustomerService implements ResourceLoaderAware
{
	private ResourceLoader resourceLoader;
 
	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}
 
	public Resource getResource(String location){
		return resourceLoader.getResource(location);
	}
}

Bean configuration file

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
   <bean id="customerService" 
           class="com.mkyong.customer.services.CustomerService" />
 
</beans>

Run it

package com.mkyong.common;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
 
import com.mkyong.customer.services.CustomerService;
public class App 
{
    public static void main( String[] args )
    {
    	ApplicationContext appContext = 
    	   new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});
 
    	CustomerService cust = 
           (CustomerService)appContext.getBean("customerService");
 
    	Resource resource = 
            cust.getResource("classpath:com/mkyong/common/testing.txt");
 
    try{
          InputStream is = resource.getInputStream();
          BufferedReader br = new BufferedReader(new InputStreamReader(is));
 
          String line;
          while ((line = br.readLine()) != null) {
     	       System.out.println(line);
          } 
          br.close();
 
    	}catch(IOException e){
    		e.printStackTrace();
    	}
 
    }
}

Now you can get the resources from a bean.

Conclusion

Without this getResource() method, you will need to deal with different resources with different solution, like File object for file system resource, URL object for URL resource. Spring really did a good job with this super generic getResource()method, it really save our time to deal with resources.

### JavaFX Maven Spring 依赖注入配置示例 在 JavaFX 项目中通过 Maven 配置 Spring 的依赖注入,可以按照以下方式实现。Spring 提供了强大的依赖注入功能,结合 JavaFX 的 GUI 工具,可以开发出功能丰富的企业级应用程序[^1]。 以下是完整的 Maven 配置和代码示例: #### 1. Maven `pom.xml` 配置 在项目的 `pom.xml` 文件中添加 Spring 和 JavaFX 的相关依赖项: ```xml <dependencies> <!-- JavaFX Dependency --> <dependency> <groupId>org.openjfx</groupId> <artifactId>javafx-controls</artifactId> <version>17.0.1</version> </dependency> <dependency> <groupId>org.openjfx</groupId> <artifactId>javafx-fxml</artifactId> <version>17.0.1</version> </dependency> <!-- Spring Core Dependency --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.10</version> </dependency> <!-- Spring AOP Dependency --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.3.10</version> </dependency> </dependencies> ``` #### 2. Spring 配置文件 创建一个 Spring 配置文件 `applicationContext.xml`,用于定义 Bean 和依赖关系: ```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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 定义一个简单的服务类 --> <bean id="helloService" class="com.example.service.HelloService"/> <!-- 定义主控制器,并注入服务 --> <bean id="mainController" class="com.example.controller.MainController"> <property name="helloService" ref="helloService"/> </bean> </beans> ``` #### 3. 示例代码 以下是 JavaFX 和 Spring 结合的示例代码: ##### 主类 ```java package com.example; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp extends Application { private ApplicationContext applicationContext; @Override public void init() throws Exception { // 初始化 Spring 上下文 applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); } @Override public void start(Stage primaryStage) throws Exception { FXMLLoader loader = new FXMLLoader(); loader.setControllerFactory(applicationContext::getBean); // 使用 Spring 创建控制器实例 Parent root = loader.load(getClass().getResource("/fxml/main.fxml").openStream()); Scene scene = new Scene(root); primaryStage.setTitle("JavaFX Spring Integration Example"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } } ``` ##### 控制器类 ```java package com.example.controller; import com.example.service.HelloService; import javafx.fxml.FXML; import javafx.scene.control.Label; public class MainController { private HelloService helloService; @FXML private Label messageLabel; public void setHelloService(HelloService helloService) { this.helloService = helloService; } @FXML public void initialize() { if (helloService != null) { messageLabel.setText(helloService.getMessage()); } } } ``` ##### 服务类 ```java package com.example.service; public class HelloService { public String getMessage() { return "Hello, JavaFX with Spring!"; } } ``` #### 4. 注意事项 - 确保 `applicationContext.xml` 文件位于类路径根目录下。 - 如果使用的是模块化 Java(Java 9+),需要在 `module-info.java` 中声明对 `javafx.controls` 和 `javafx.fxml` 的依赖[^1]。 - 如果需要更复杂的依赖注入,可以考虑使用注解(如 `@Autowired`)代替 XML 配置[^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值