IOC容器创建对象
- 在pom.xml添加spring依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
2.创建配置文件,比如spring.xml
3.在spring.xml中配置bean标签,IOC容器通过加载bean来创建对象
4.调用API获取IOC创建的对象
IOC容器创建对象同样有两种,无参构造和有参构造
无参创建我们可以理解为无参构造函数创建对象,不对其进行任何属性赋值,有参便是通过有参构造函数创建对象,将对其属性进行一些赋值。
- 无参构造函数创建对象
<!--配置Student对象,IOC通过这个bean来创建对象-->
<bean id="stu" class="entity.Student"</bean>
<!--id可以理解为这个bean的名字,后面会用到,class是上面创建Student类的目录路径-->
API获取对象,有两个方法,一种是id,一种是运行时类
1.通过id获取对象
public class ApplicationContext{
public static void main(String[] args){
AbstractApplicationContext applicationContext = new ClasspathXmlApplicationContext("spring.xml");
//通过id获取对象
Student stu = (Student)applicationContext.getBean("stu");
System.out.pritnln(stu);
Student stu1 = applicationContext.getBean(Student class); //声明强转
System.out.pritnln(stu1);
}
}
通过上图我们可以看到,通过无参构造方式创建的对象属性值都是0或null,这也证明了一点IOC确实是通过构造函数来创建对象的,那么我们让其属性具有一些值呢?这里我们需要在bean标签中添加property属性,我们可以理解为传统方式的属性调用。下面我们举例说明以下:
<bean id = "stu" class = "entity.Student">
<property name = "id" value="1"></property>
<property name = "name" value="xf"></property>
</bean>
- 有参构造方式创建对象
1.实体类中创建有参构造
public class Student{
private int id;
private String name;
private int age;
//创建有参构造函数
public Student(int id,String name,int age){
this.id = id;
this.name = name;
this.age = age;
}
}
2.在spring.xml中进行配置
<bean id="stu" class="entity.Student">
<constructor-arg name="id" value="3"></constructor-arg>
<constructor-arg name="name" value="jacob"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
</bean>
<!--注意这里一定要写constructor-arg,不然会报错,报错原因是当我们写出有参构造函数时,程序中默认的无参就不存在了-->
在spring.xml中,通过ref属性将其他bean赋给当前bean对象,这种方式叫做依赖注入(DI),是spring非常重要的机制,DI是将不同对象进行关联的一种方式,是IOC的具体实现方式,所以IOC和DI通常是紧密结合在一起的,因此一般说IOC包括DI。
xfgg
发布了9 篇原创文章 · 获赞 0 · 访问量 298
私信
关注