1.导如依赖
现在想要使用核心容器IOC这个模块,那么就需要导入这个模块所需要的jar包,同时Spring运行的时候需要一个日志文件,因此还需要导入一个和日志相关的jar包
为了方便起见,再导入一个lombok.jar,这个jar包可以使用注解的方式写实体类的构造方法,setter(),getter(),toString()方法等。
<!--导入IOC核心容器4个jar包-->
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<!--导入日志包,没有会回报错-->
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
<scope>provided</scope>
</dependency>
</dependencies>
2.写配置文件spring.xml
spring的配置文件中,集合了spring的ioc容器所管理的所有组件
创建spring.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--注册一个Person对象,Spring会自动创建这个Person对象-->
<!--
一个bean标签可以创建一个组件(对象,类)
class:要注册的组件的全类名
id:这个对象的唯一标识
-->
<bean id="person" class="com.hh.pojo.Person">
<!--
使用property标签为这个Person对象的属性赋值
name:属性名
value:属性值
-->
<property name="lastName" value="张三"/>
<property name="age" value="23"/>
<property name="gender" value="男"/>
</bean>
</beans>
3.写一个测试类
public class MyTest {
@Test
public void test(){
//根据spring的配置文件得到ioc容器对象
ApplicationContext context =
new ClassPathXmlApplicationContext("spring.xml");
//根据id获取Person对象
Person person = context.getBean("person",Person.class);
System.out.println(person);
}
}
由打印结果可以看出,不仅创建了对象,还通过set方法为对象的属性赋值了。
4.关于上面程序的细节说明
1.ApplicationContext是IOC容器的接口
2.容器中对象的创建在容器创建完成的时候就已将创建好了
3.同一个组件在IOC容器中是单实例的
4.
5.ioc容器在创建这个组件对象的时候,会利用Person类的set()方法为属性进行赋值