Advertising:
Discusión:Spring Framework 000 - Instanciar Beans con Spring Framework
Jump to navigation
Jump to search
Si usamos:
Resource resource = new FileSystemResource("beans.xml");
El recurso debe ser colocado manualmente después de deployar en la carpeta desde donde es invocado el programa/proyecto. Si no lo hacemos, cuando ejecutemos saldrá un error como este:
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from file [D:\workspace6\SpringPrueba1\beans.xml]; nested exception is java.io.FileNotFoundException: beans.xml (The system cannot find the file specified) Caused by: java.io.FileNotFoundException: beans.xml (The system cannot find the file specified)
Sino podemos dejar el xml en la misma carpeta donde esta el class invocante (ya las IDEs mas conocidas como Eclipse lo hace por nosotros), y obtener el recurso asi:
// Objeto util solamente para obtener el path del xml PruebaBeanContainer prueba = new PruebaBeanContainer(); Resource resource = new UrlResource(prueba.getClass().getResource("beans.xml"));
Quedando el fuente:
package com.chuidiang.pruebas.spring; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; public class PruebaBeanContainer { public static void main(String[] args) { // Objeto util solamente para obtener el path del xml PruebaBeanContainer prueba = new PruebaBeanContainer(); Resource resource = new UrlResource(prueba.getClass().getResource("beans.xml")); BeanFactory factory = new XmlBeanFactory(resource); System.out.println(factory.getBean("Juan")); System.out.println(factory.getBean("Pedro")); } }