使用myeclipse自动反转
- 新建java项目:sday01
- 右击项目
- 点击 Add Spring Capabilities...
项目如下:
但是一般开发中不用翻转
如下:
手动添加spring
1、引入spring的jar文件
libs/spring-beans-3.2.2.RELEASE.jarlibs/spring-context-3.2.2.RELEASE.jar
libs/spring-context-support-3.2.2.RELEASE.jar
libs/spring-core-3.2.2.RELEASE.jar
libs/spring-expression-3.2.2.RELEASE.jar
需要:
commons-logging-1.1.1.jar
2、需要添加spring的配置文件
配置文件的名称可以随便起名,但是最好有实际意义。例如:
spring-dao.xml
spring-service.xml
spring.xml
3、spring配置文件 怎么引入 beans约束
- ---spring-framework-3.2.2.RELEASE-dist/spring-framework-3.2.2.RELEASE/docs/spring-framework-reference/html/index.html
- 帮助文档 目录中:5.2.1. Configuration metadata 点击进去
<?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">
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>
4、下面就有实例化 :容器
// 读取 classes 路径下面的文件 参数 动态参数、单个参数、数组 、可以使用通配符等ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
5、在容器中获取bean
HelloDao helloDao = (HelloDao) context.getBean("helloDaoImpl");HelloService helloService = context.getBean("helloServiceImpl", HelloService.class);
6、有关spring配置文件 多个的时候 可以采用import标签导入一个文件中
<import resource="spring-dao.xml"/><import resource="spring-service.xml"/>
7、spring容器 管理bean
bean 属性id: 标识 唯一
class: 类
scope:作用域 singleton prototype request session
lazy-init:default=false ,false ,true
lazy-init结合scope=singleton使用
scope="singleton" lazy-init="default" -->说明:容器已经加载就实例化对象
scope="singleton" lazy-init="true" -->说明:容器已经加载当使用到该对象的时候,实例化该对象