IOC创建对象的三种方式(构造器注入)
默认使用的是无参构造器但是当有参构造器存在时,无参构造器便没有用
1.第一种:下标
属性是对象:
构造器:
1 | public UserServiceImpl (UserDao userdao) { |
1 | <bean id="UserServiceImpl" class="com.saxon.Service.UserServiceImpl"> |
属性不是对象:
构造器:
1 | public UserServiceImpl (int a) { |
1 | <bean id="UserServiceImpl" class="com.saxon.Service.UserServiceImpl"> |
index指的是构造器属性的下标,如果不是对象就用value直接赋值;
2.第二种:根据属性的类型(不推荐)
1 | public UserServiceImpl (int a,String b) { |
1 | <bean id="UserServiceImpl" class="com.saxon.Service.UserServiceImpl"> |
1 | <bean id="UserServiceImpl" class="com.saxon.Service.UserServiceImpl"> |
当存在多个相同数据的时候赋值根据你的语句顺序来赋值;
不推荐原因:当我们的类名过于复杂的时候,就很容易把类名写错;
3.第三种:根据属性的名字
1 | public UserServiceImpl (UserDao userDao) { |
1 | <bean id="UserServiceImpl" class="com.saxon.Service.UserServiceImpl"> |
是对象就用ref,不是对象直接用value;
我们所有的bean在注册的时候,就全部被实例化过了,所以我们直接取过来就可以使用,所以他只会实例化一个对象,不会再new一个,下面运行的结果是true
1 | ApplicationContext context = new ClassPathXmlApplicationContext ("applicationContent.xml"); |
ApplicationContext就是一个容器,你需要啥就拿啥;



