IOC创建对象的三种方式(构造器注入)

默认使用的是无参构造器但是当有参构造器存在时,无参构造器便没有用

1.第一种:下标

属性是对象:

构造器:

1
2
3
public UserServiceImpl (UserDao userdao) {
this.userDao=userdao;
}
1
2
3
4
<bean id="UserServiceImpl" class="com.saxon.Service.UserServiceImpl">
<property name="userDao" ref="OralceUserImpl"/>
<constructor-arg index="0" ref="OralceUserImpl"/>
</bean>

属性不是对象:

构造器:

1
2
3
public UserServiceImpl (int a) {
System.out.println (a);
}
1
2
3
4
<bean id="UserServiceImpl" class="com.saxon.Service.UserServiceImpl">
<property name="userDao" ref="OralceUserImpl"/>
<constructor-arg index="0" value="0"/>
</bean>

index指的是构造器属性的下标,如果不是对象就用value直接赋值;

2.第二种:根据属性的类型(不推荐)

1
2
3
public UserServiceImpl (int a,String b) {
System.out.println (a+"&"+b);
}
1
2
3
4
5
<bean id="UserServiceImpl" class="com.saxon.Service.UserServiceImpl">
<property name="userDao" ref="OralceUserImpl"/>
<constructor-arg type="int" value="0"/>
<constructor-arg type="java.lang.String" value="1"/>
</bean>
1
2
3
4
<bean id="UserServiceImpl" class="com.saxon.Service.UserServiceImpl">
<property name="userDao" ref="OralceUserImpl"/>
<constructor-arg type="com.saxon.Dao.UserDao" ref="OralceUserImpl"/>
</bean>

当存在多个相同数据的时候赋值根据你的语句顺序来赋值;

不推荐原因:当我们的类名过于复杂的时候,就很容易把类名写错;

3.第三种:根据属性的名字

1
2
3
4
public UserServiceImpl (UserDao userDao) {
this.userDao = userDao;
}

1
2
3
4
 <bean id="UserServiceImpl" class="com.saxon.Service.UserServiceImpl">
<property name="userDao" ref="OralceUserImpl"/>
<constructor-arg name="userDao" ref="OralceUserImpl"/>
</bean>

是对象就用ref,不是对象直接用value;

我们所有的bean在注册的时候,就全部被实例化过了,所以我们直接取过来就可以使用,所以他只会实例化一个对象,不会再new一个,下面运行的结果是true

1
2
3
4
ApplicationContext context = new ClassPathXmlApplicationContext ("applicationContent.xml");
UserServiceImpl userServiceImpl = (UserServiceImpl)context.getBean ("UserServiceImpl");
UserServiceImpl userServiceImp2 = (UserServiceImpl)context.getBean ("UserServiceImpl");
System.out.println (userServiceImpl==userServiceImp2);

ApplicationContext就是一个容器,你需要啥就拿啥;