基本原理 - 容器和bean

在Spring中,那些组成你应用程序的主体(backbone)及由Spring IoC容器所管理的对象,被称之为bean。 简单地讲,bean就是由Spring容器初始化、装配及管理的对象,除此之外,bean就与应用程序中的其他对象没有什么区别了。

也就是说,其实spring 就是在加载配置文件beans.xml的时候,通过反射机制,去实例化<bean>标签里面的类的过程。这里可以通过在类的默认无参构造方法中写点东西判断出来。

1. 配置元数据

基于XML的配置元数据的基本结构:beans.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-2.5.xsd"> <bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean> <bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean> <!-- 更多的bean的时候 在引用的xml文件一定是要带spring dtd头的文件-->
<import resource="services.xml"/>
</beans>

services.xml

在配置文件里面命名其实id 和name都是一样的

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="userService" name="userService" class="com.sun.service.UserService">
<property name="name">
<value>sunxin</value>
</property>
</bean> </beans>

2. 实例化容器

ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] {"beans.xml"});

2. bean的别名

<!--name指向的是已经存在该id的bean,alias是给给该bean命的别名-->
<alias name="userService" alias="user"/>

调用可以通过:

    UserService us  = (UserService) app.getBean("user");

最新文章

  1. 开始学nodejs —— 调试篇
  2. event.keyCode ,event.which ,event.charCode (2016-12-27 16:17:16)
  3. aviator使用手册在线
  4. jQuery仿京东无限级菜单HoverTree
  5. java 22 - 3 多线程的概述以及其它所涉及的东西(看)
  6. .net自动生成数据库表的类
  7. [转]mac 10.9.4下配置apache
  8. [原创]java WEB学习笔记55:Struts2学习之路---详解struts2 中 Action,如何访问web 资源,解耦方式(使用 ActionContext,实现 XxxAware 接口),耦合方式(通过ServletActionContext,通过实现 ServletRequestAware, ServletContextAware 等接口的方式)
  9. php中的 == 和 ===
  10. node-firefox 二三事
  11. JMX-JAVA进程监控利器
  12. Android开发环境搭建(windows OS)之补充
  13. fullcalender
  14. Js特效总结
  15. 精读《javascript高级程序设计》笔记一——基本概念
  16. Maven-01 安装maven
  17. Asp,NET控制文件上传的大小
  18. html5 storage事件
  19. vue.js+socket.io+express+mongodb打造在线聊天
  20. Python小代码_3_购物车

热门文章

  1. Word对象模型 (.Net Perspective)
  2. Apache虚拟主机(vhost)配置教程
  3. golang安装卸载 linux+windows+raspberryPI 平台
  4. struct ifreq结构体与ip,子网掩码,网关等信息
  5. SQL Server查询性能优化——覆盖索引(一)
  6. HUFFMAN 树
  7. 【原】Redis基本操作
  8. Android 多线程 异步加载
  9. mysql 中文乱码的解决办法
  10. 拍照返回的bitmap太小