Spring IOC学习整理
1.1容器架构思想:
1.2 IOC容器创建与获得Bean对象:
步骤:
第一步: 依赖注入
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.19.RELEASE</version>
</dependency>
第二步:编写核心配置文件beans.xml ,导入bean的约束
<?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">
//第三步:在beans.xml中书写bean的定义
// Id:容器中bean对象的唯一标志
// Class:bean对象的类型,全限定名
<bean id="helloService" class="com.chinasofti.HelloService" ></bean>
</beans>
```java
第四步:获取applicationContext(spring容器,ioc容器)
ApplicatContext接口代表的容器对象,但是接口不能创建对象,最终是由实现类创建对象,也就是它的实现类才是真实的容器,真实的管理bean的生命周期.
//获取容器对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
第五步:从容器中获取bean
还有其他方法,自己用
//获取bean对象
HelloService helloService1 = (HelloService) context.getBean("helloService");
第六步:调用相应的方法
//调用方法
helloService1.sayHello("jack");
如果想要演示XmlWebApplicationContext,在web包下,需要导入web依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.19.RELEASE</version>
</dependency>