Spring Boot应用程序上下文不起作用

时间:2019-03-02 13:49:17

标签: java spring

在使用Spring BeanFactory和ApplicationContext bean提供程序时,依赖注入会产生不同的结果。

我正在使用Triangle类:

public class Triangle {
  private String type;
  public String getType() {
    return type;
  }
  public void setType(String type) {
    this.type= type;
  }
  public void draw(){
    System.out.println(getName() + "Triangle")
  }
}

我的主要课程是:

public class DrawingApp {
  public static void main(String[] args) {
    BeanFactory factory = new XmlBeanFactory( new FileSystemResource("spring.xml"));
    Triangle triangle = (Triangle) factory.getBean("triangle");
    triangle.draw();

    ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
    Triangle triangle1 = (Triangle) context.getBean("triangle");
    triangle1.draw();
  } 
}

我的spring.xml文件是

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" 
 "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
   <beans> 
     <bean id = "triangle" class = "org.package.Triangle">
     <property name="type" value="equilateral"/>
   </bean>
 </beans>  

输出应为:

equilateral triangle
equilateral triangle

但是我得到的输出是:

equilateral triangle
null triangle

1 个答案:

答案 0 :(得分:0)

除了编译问题(例如重复的变量..),并假设这些问题已解决,Spring为您提供了不同的bean;您可以通过以下方式检查两个版本是否确实在使用相同的 xml上下文文件:

try {
    FileSystemResource file_res= new FileSystemResource("spring.xml");
    ClassPathResource classpath_res = new ClassPathResource("spring.xml");
    System.out.printf("file resource=%s location=%s%n", file_res, file_res.getURL());
    System.out.printf("classpath resource=%s location=%s%n", classpath_res, classpath_res.getURL());
} catch (IOException e) {
    e.printStackTrace(System.out);
}

例如,它们最终可能会加载不同的配置文件并给出(注意),这些文件来自不同的地方,一个来自项目主目录,一个是目标/类)

file resource=file [C:\...\spring.xml] location=file:/C:/.../use-spring/spring.xml
classpath resource=class path resource [spring.xml] location=file:/C:/.../use-spring/target/classes/spring.xml