-
编写流程(基于XML)
- 导入jar包: 4+1 -> beans / core / context / expression | commons-logging
- 编写目标类:dao和service
- spring配置文件
- IoC:
<bean id="" class=""> - DI:
<bean><property name="" value="" ref=""></bean> - 实例化方式:
- 默认构造
- 静态工厂:
<bean id="" class="工厂类" factory-method="静态方法"/> - 实例工厂:
<bean id="" factory-bean="工厂id" factory-method="方法">
- 作用域:
<bean id="" scope="singleton|porotype"> - 生命周期:
<bean id="" class="" init-method="" destory-method="">- 后处理bean BeanPostProssor接口,
<bean class="注册">对容器中所有的bean都生效
- 后处理bean BeanPostProssor接口,
- 属性注入
- 构造方法注入:
<bean><constructor-arg index="" type=""> - setter方法注入:
<bean><property> - p 命名空间:简化
<property> <bean p:属性名="普通值" p:属性名-ref="引用值">注意生明命名空间 - SpEL:
<property name="" value="#{表达式}">- #{123} #{‘abc’}
- #{beanId.propName?methodName()}
- #{T(类).静态方法|字段}
- 集合
- 数组
<array> - List
<list> - Set
<set> - Map
<map><entry key="" value=""> - Propertes
<props><prop key="">....
- 数组
- 构造方法注入:
- IoC:
- 核心api
- BeanFactory:延迟实例化bean,第一次调用getBean
- ApplicationContext 一般常用,功能更强
- ClassPathXmlApplicationContext 加载 classpath xml文件
- FileSystemXmlApplicationContext 加载 指定盘符文件,ServletContext.getRealPath();
-
注解
- 扫描含有注解的类
1.
<context:component-scan base-package=""> - 常见的注解
- Component 组件,任意bean
- WEB
- @Controller web层
- @Service service层
- @Repository dao层
- 注入 --》 字段或者setter方法
- 普通值:@Value
- 引用值:
- 类型:@Autowired
- 名称1:@Autowired @Qualifier("名称")
- 名称2:@Resource(“名称”)
- 作用域:@Scope("prototype")
- 生命周期:
- 初始化:@PostConstruct
- 销毁方法:@PreDestroy
- 扫描含有注解的类
1.
-
注解和xml混合使用
-
将所有的bean都配到xml中
<bean id="" class="">
-
将所有的依赖都使用注解
-
@Autowired
默认不生效。为了生效,需要在xml配置<context:annotation-config >
-
-
<context:component-scan base-package="com.adolph.web"></context:component-scan>
<context:annotation-config></context:annotation-config>
1. 一般情况两个注解不一起使用
2. 注解一,扫描含有注解(@Component等)类,注入注解自动生效
3. 注解为,只在xml和注解(注入)混合使用时,使注入注解生效。