关于构造方法
一个类中有一个构造方法,就用这个构造方法
一个类中有多个构造方法且包括无参构造方法,则用默认的那个无参构造方法
一个类中有多个构造方法且没有包括无参构造方法,则报错
一个类中没有写构造方法,则用默认的无参构造方法
一个类中有多个构造方法,可以有@Autowired指定使用哪个构造方法
先判断用哪个构造方法,然后再判断构造方法入参对应的那个Bean,在容器中查找这个Bean时 先ByType 就是通过类名去找容器中的这个类,找到之后再通过参数的名字去容器中找到对应名字的对象
单例bean为了保证同一个名字对应唯一的对象,底层用了单例池(即ConcurrentHashMap),即一个key对应一个value,因此在外部用多个applicationContext.getBean("orderService")拿对象时,都是通过orderService这个key去获取同一个value。
单例对象存放在 Map
map.put("orderService",orderService);
map.put("orderService1",orderService);
map.put("orderService2",orderService);
OrderService是一个单例Bean 并不代表整个容器里面只能有一个OrderService类型的对象,只是代表通过applicationContext.getBean(“orderService”)拿到的都是同一个对象,还是可以创建多个不同名的OrderService类型的Bean。
public static void main(String[] args){ AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class); applicationContext.getBean("orderService");//若是单例bean,则这里获取的四个orderService都是同一个对象; applicationContext.getBean("orderService");//若是原型bean,则这里获取的四个orderService是四个不同的对象; applicationContext.getBean("orderService"); applicationContext.getBean("orderService"); applicationContext.getBean("orderService1"); applicationContext.getBean("orderService2"); }
如果OrderService是一个原型Bean的话,那么通过applicationContext.getBean(“orderService”)拿到的不是同一个对象。

浙公网安备 33010602011771号