spring resource通配符

时间:2025-02-13 15:36:27
public class ResourceBean3Controller{
	
	private Resource resource;
    public Resource getResource() {
        return resource;
    }
    public void setResource(Resource resource) {
         = resource;
    }
    
    @Test
    public void test() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("/");
        ResourceBean3Controller resourceBean1 = ("resourceBean1", );
        ResourceBean3Controller resourceBean2 = ("resourceBean2", );
        (() instanceof ClassPathResource);
        (() instanceof ClassPathResource);
    }
    
    
	/*使用路径通配符加载Resource
	Spring提供了一种更强大的Ant模式通配符匹配,从能一个路径匹配一批资源。
	Ant路径通配符支持“?”、“*”、“**”,注意通配符匹配不包括目录分隔符“/”:
	“?”:匹配一个字符,如“config?.xml”将匹配“”;
	“*”:匹配零个或多个字符串,如“cn/”将匹配“cn/javass/”,但不匹配匹配“cn/”;而“cn/config-*.xml”将匹配“cn/”;
	“**”:匹配路径中的零个或多个目录,如“cn/*”将匹配“cn /”,
	也匹配“cn/javass/spring/”;而“cn/javass/config-**.xml”将匹配“cn/javass/”,即把“**”当做两个“*”处理。
	*/
    @Test
    public void testClasspathPrefix()  {
    	ApplicationContext ctx = new ClassPathXmlApplicationContext("/resource*.xml");
        ResourceBean3Controller resourceBean1 = ("resourceBean1", );
        ResourceBean3Controller resourceBean2 = ("resourceBean2", );
        (() instanceof ClassPathResource);
        (() instanceof ClassPathResource);          
    }
    
    @Test
    public void testAsteriskPrefix () throws IOException {
         ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();      
         //将加载多个绝对匹配的所有Resource
        //然后进行遍历模式匹配
        Resource[] resources=("/*.properties");
        if(>0){
        	(123);
        	dumpStream(resources[0]);
        }
        
        ( > 0);
        //将加载多个模式匹配的Resource
        resources = ("/");
        ( > 0);  
    }
    
    private void dumpStream(Resource resource) {
        InputStream is = null;
        try {
            //1.获取文件资源
            is = ();
            //2.读取资源
            byte[] descBytes = new byte[()];
            (descBytes);
            (new String(descBytes));
        } catch (IOException e) {
            ();
        }
        finally {
            try {
                //3.关闭资源
                ();
            } catch (IOException e) {
            }
        }
    }
    
    /**
     * 注入
     */
    @Test
    public void testClasspathPrefix2()  {
    	ApplicationContext ctx = new ClassPathXmlApplicationContext("/bean3Resource*.xml");
        ResourceBean3Controller resourceBean1 = ("resourceBean1", );
        ResourceBean3Controller resourceBean2 = ("resourceBean2", );
        (() instanceof ClassPathResource);
        (() instanceof ClassPathResource);          
    }
     
}

<!-- Spring提供了一个PropertyEditor “ResourceEditor”用于在注入的字符串和Resource之间进行转换。
	因此可以使用注入方式注入Resource。	 -->
	<bean  class=".ResourceBean3Controller">
	   <property name="resource" value=""/>
	</bean>
	<bean  class=".ResourceBean3Controller"> 
		<property name="resource"
		value="classpath:"/>
	</bean>