Bean的作用域

  1. // src/com.lijunyang.model.Person
  2. public class Car {
  3. private String brand;
  4. private double price;
  5. }
  6. // src/com.lijunyang.test.Main.java
  7. public class Main {
  8. public static void main(String[] args) {
  9. ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-autowire.xml");
  10. Car car = (car) ctx.getBean("car");
  11. Car car2 = (car) ctx.getBean("car");
  12. System.out.println(car === car2);
  13. /*
  14. 当配置文件的bean的scope未设置时,结果为true
  15. scope="prototype" 原型的,容器初始化时不创建,只有当每次获取bean的时候都创建一个,结果为false
  16. scope="singleton" 单例的,容器初始化时创建 结果为true
  17. */
  18. }
  19. }
  20. // src/beans-spring.xml
  21. <?xml version="1.0" encoding="UTF-8"?>
  22. <beans xmlns="http://www.springframework.org/schema/beans"
  23. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  24. xmlns:context="http://www.springframework.org/schema/context"
  25. xsi:schemaLocation="http://www.springframework.org/schema/beans
  26. http://www.springframework.org/schema/beans/spring-beans.xsd
  27. http://www.springframework.org/schema/context
  28. http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  29. <bean id="car" class="com.lijunyang.model.Car"
  30. // scope="" // singleton | session | request | prototype
  31. p:brand="Audi" p:price="200000" />
  32. </beans>