House.java 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package com.sf.ioc.anno;
  2. import jakarta.annotation.Resource;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Component;
  5. /**
  6. * 教室
  7. * 构造类和类之间的组合关系 区别于继承关系
  8. */
  9. @Component
  10. // <bean id="house">
  11. public class House {
  12. /**
  13. * 教室里有一把椅子
  14. */
  15. @Autowired
  16. private Chair chair;
  17. // 使用@Autowired 是先根据类型来匹配对象
  18. // 如果类型对应的对象有多个 可以结合 @Qualifier来声明名字
  19. // 使用@Resource 是先根据名字来匹配对象
  20. // Could not autowire. There is more than one bean of 'Plane' type.
  21. // @Autowired @Qualifier("desk")
  22. // @Autowired @Qualifier("box")
  23. // @Resource(name = "desk")
  24. // private Plane plane;
  25. @Resource
  26. private Plane desk;
  27. public House() {
  28. System.out.println("House 构造器");
  29. }
  30. public void setChair(Chair chair) {
  31. System.out.println("House setChair");
  32. this.chair = chair;
  33. }
  34. @Override
  35. public String toString() {
  36. return "House{" +
  37. "chair=" + chair +
  38. ", plane=" + desk +
  39. '}';
  40. }
  41. }