学习笔记,如有错误,请多多指正!
4. IOC创建对象的方式
新建实体类:
package com.nych.entity;
public class User {
private String name;
public User(){
System.out.println("User无参构造");
}
public User(String name) {
this.name = name;
System.out.println("User有参构造");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
使用spring创建对象的方式:
-
使用无参构造创建对象(默认)
<bean id="user" class="com.nych.entity.User"> <property name="name" value="张三"/> </bean>
-
使用有参构造创建对象
-
方法一:通过下标赋值
<bean id="user" class="com.nych.entity.User"> <constructor-arg index="0" value="张三"/> </bean>
-
方法二:通过类型赋值
<bean id="user" class="com.nych.entity.User"> <constructor-arg type="java.lang.String" value="张三"/> </bean>
-
方法三: 通过参数名赋值
<!-- 通过参数名赋值--> <bean id="user" class="com.nych.entity.User"> <constructor-arg name="name" value="张三"/> </bean>
-
测试:
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) context.getBean("user");
User user2 = (User) context.getBean("user");
System.out.println(user.getName());
System.out.println("user == user2: " + (user == user2));
}
}
结果:
- spring默认单例模式
再新建实体类UserTwo
public class UserTwo {
private String name;
public UserTwo() {
System.out.println("UserTwo被创建了!");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
在spring容器中注册
<bean id="userTwo" class="com.nych.entity.UserTwo"/>
再次运行测试:
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) context.getBean("user");
User user2 = (User) context.getBean("user");
System.out.println(user.getName());
System.out.println("user == user2: " + (user == user2));
}
}
结果:
**结果分析:**即使没有调用UserTwo,UserTwo的对象也会被创建。
- 小节总结
- spring默认单例模式
- 在配置文件被加载时,容器中管理的类对象就被创建了