spring 资源访问

spring 资源访问

复制代码
        Resource resource=null;
        //访问网络资源
        resource=new UrlResource("file:bool.xml");
        //访问类加载路径下的资源
        resource=new ClassPathResource("book.xml");
        //访问文件系统资源
        resource=new FileSystemResource("book.xml");
        //访问字节数组资源
        String str="";
        byte[] fileBytes=str.getBytes();
        resource=new ByteArrayResource(fileBytes);
        //resource=new ServletContextResource()
        //resource=new InputStreamResource()
        InputStream inputStream= resource.getInputStream();
        boolean exists=resource.exists();
        boolean isOpen=resource.isOpen();
        String description=resource.getDescription();
        File file=resource.getFile();
        URL url= resource.getURL();

        ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
        resource=ctx.getResource("book.xml");
        
        ctx=new FileSystemXmlApplicationContext("beans.xml");
        ctx=new FileSystemXmlApplicationContext("/beans.xml");
        //加载相对路径
        ctx=new FileSystemXmlApplicationContext("file:beans.xml");
        //加载绝对路径
        ctx=new FileSystemXmlApplicationContext("file:/beans.xml");
        ctx=new FileSystemXmlApplicationContext("classpath:beans.xml");
        //加载多个配置文件
        ctx=new FileSystemXmlApplicationContext("classpath*:beans.xml");
        ctx=new ClassPathXmlApplicationContext("beans*.xml");
        ctx=new FileSystemXmlApplicationContext("classpath*:bean*.xml");        
复制代码

 

配置管理

复制代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

//修饰一个Java配置类
@Configuration
//导入XML配置
@ImportResource("classpath:/beans.xml")
public class AppConfig {
    //修饰一个方法,将该方法的返回值定义成容器中的一个Bean
    @Bean
    public Person person(){
        
    }
    @Bean(name = "stoneAxe")
    public Axe stoneAxe(){
        
    }
    @Bean(name = "steelAxe")
    public Axe steelAxe(){
        
    }
}
复制代码

 

posted @   uptothesky  阅读(123)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
点击右上角即可分享
微信分享提示