1、IOC简介
学术:IoC就是一个对象定义其依赖关系而不创建它们的过程。
目的:省去new 创建对象的过程。在之前我们使用一个class,需要先 aaa = new bbb()一个对象。用了IOC,直接通过配置或者注释的手段,注册到容器中。无需new创建,即可直接使用 bbb()对象方法。
2、代码说明
(1)导包
核心容器
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
commons-logging-1.1.3.jar
Spring运行的时候依赖一个日志包;没有就报错;
(2)代码
package com.atguigu.bean;
public class Person {
private String lastName;
private Integer age;
private String gender;
private String email;
public Person() {
super();
// TODO Auto-generated constructor stub
System.out.println("person创建了...");
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
System.out.println("setLastName..."+lastName);
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String toString() {
return "Person [lastName=" + lastName + ", age=" + age + ", gender="
+ gender + ", email=" + email + "]";
}
}
(3)写配置
spring的配置文件中,集合了spring的ioc容器管理的所有组件(会员清单);
创建一个Spring Bean Configuration File(Spring的bean配置文件);
<!-- 注册一个Person对象,Spring会自动创建这个Person对象 -->
<!--
一个Bean标签可以注册一个组件(对象、类)
class:写要注册的组件的全类名
id:这个对象的唯一标示;
-->
<bean id="person01" class="com.atguigu.bean.Person">
<!--使用property标签为Person对象的属性赋值
name="lastName":指定属性名
value="张三":为这个属性赋值
-->
<property name="lastName" value="张三"></property>
<property name="age" value="18"></property>
<property name="email" value="zhangsan@atguigu.com"></property>
<property name="gender" value="男"></property>
</bean>
(4)test实现
@Test
public void test() {
//ApplicationContext:代表ioc容器
//ClassPathXmlApplicationContext:当前应用的xml配置文件在 ClassPath下
//根据spring的配置文件得到ioc容器对象
//ApplicationContext ioc = new ClassPathXmlApplicationContext("com/atguigu/bean/ioc.xml");
ApplicationContext ioc = new ClassPathXmlApplicationContext("ioc.xml");
//容器帮我们创建好对象了;
System.out.println("容器启动完成....");
Person bean = (Person) ioc.getBean("person01");
System.out.println(bean);
}
来源:CSDN
作者:Luke Zhou
链接:https://blog.csdn.net/zhou164200/article/details/104106646