您的位置:首页 > 编程语言 > Java开发

spring学习笔记(一)

2016-01-10 20:02 387 查看
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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: