1.spring环境搭建
首先搭建环境
Beans Core Context SpEL
还有logging包
2.spring概念介绍
IOC:Inverse of Control
反转控制
自己创建对象—– >spring创建对象 然后取出来
DI:Dependency Injection 依赖注入
Application 每次启动时创建容器中所有的对象
3.Bean元素
<bean name="user1" class="wait.of.wind.User" scope="singleton"
init-method="init" destroy-method="destory">
<property name="name" value="ziang"></property>
<property name="age" value="22"></property>
</bean>
scope: prototype 多例模式 就是每次getBean都是新的对象
singleton 默认值 单例模式
3.1属性注入
上边已经有set方式的属性注入
3.1.1构造方法注入
<bean name="user1" class="wait.of.wind.User" >
<constructor-arg name="name" value="ziang" index="0" type="java.lang.String" ref=""></constructor-arg>
<constructor-arg></constructor-arg>
</bean>
没啥好解释的
index是索引 从0开始
3.1.2 p命名空间注入
首先需要导入约束
<bean name="user2" class="wait.of.wind.User" p:name="" p:age-ref=""></bean>
3.1.3SPEL注入
<property name="name" value="#{user1.name}"></property>
这个不能用引用类型
3.1.4复杂类型注入
数组注入
<property name="arr">
<array>
<value></value>
<ref bean="user1"/>
</array>
</property>
list注入
<property name="">
<list>
<value></value>
<ref bean="user1" />
</list>
</property>
map注入
<property name="map">
<map>
<entry key="" value=""></entry>
<entry key-ref="" value-ref=""></entry>
</map>
</property>
properties注入
<property name="">
<props>
<prop key="root">root</prop>
</props>
</property>
4.用工具类获得ApplicationContext
需要导入web包和struts2包
ServletContext servletContext = ServletActionContext.getServletContext();
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
还需要在web.xml中配置listener和配置一个listener用的context-param
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:apoplicationContext.xml</param-value>
</context-param>