IOC: 控制反转:
将对象的实例化交给spring 容器来完成。
1.启动框架
//BeanFactory: spring 容器,XmlBeanFactory:通过xml配置的spring工厂
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);
2. 从容器中拿bean
a. 按照类型拿bean
factory.getBean(HelloWorld.class);
b. 按照名字拿bean
hello=(HelloWorld)factory.getBean("hello");
c. 按照名字和类型拿bean
hello=factory.getBean("hello", HelloWorld.class);
spring容器要实例化哪些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">
<!-- 配置需要Spring 实力化(管理)的对象
id: 给bean 起一个唯一的名字,为了从spring 容器中拿对象
-->
<bean id="hello" class="com.zhq.controller.HelloWorld">
</bean>
</beans>