1、spring是为了解决企业级应用开发复杂性的开源框架;
轻量级的控制反转IOC 又称依赖注入DI(低耦合)和面向切面AOP(内聚性)的容器框架;
作为容器,包含并管理应用对象的配置和生命周期;
作为框架,将简单的组件配置、组合成复杂的应用。
在spring中,所有对象都称为bean.
2、两大部分IOC+AOP :
(1) IOC : 应用程序本身不负责依赖对象的创建和维护,由外部容器(spring)负责创建和维护。
就是要使用一个接口中的方法,必须实现他的实现类,当他有多个实现类时,我们不用管他用的是哪个实现类,只需要知道是这个接口就ok,至于用哪个由spring容器传来的实现类管理和维护。
类似如下:
InterfaceImplFactory{
AInterface create(Object condition) {
if(condition = condA){ return new AInterfaceImpA(); }
else if(condition = condB){ return new AInterfaceImpB(); }
else{ return new AInterfaceImp(); } }}
spring注入: 两种方式
<!-- 设值注入 -->
<bean id="helloWorldService" class="com.spring.business.HelloWorldService">
<qualifier value="main11" ></qualifier>
<!-- <property name="helloWorldDao" ref="helloWorldDao"></property> -->
</bean>
<!-- 构造器注入 -->
<bean id="helloWorldService1" class="com.spring.business.HelloWorldService"scope="singleton">
<constructor-arg name="helloWorldDao1" ref="helloWorldDao"></constructor-arg>
</bean>
<!--注:构造器注入跟 name 对应的是构造函数参数的变量名 -->
Bean装配的方式:默认byName , byType , Constructor
<Beans ..... default-autowire="default/byName/byType/Constructor ">
Resource 类 获取文件资源 (classPath: / file: / “url”) 三种方式
bean管理的注解实现
@Repository 注解Dao类
@Service 注解Service类
@Controller 注解controller类
@Component 通用注解 可用于任何bean
注解说明
@Required 用于注解Bean的setter方法
@Autowired 注解setter、构造器、成员变量
自动扫描注册Bean的方法如下
<context:annotation-config></context:annotation-config>
<!-- 禁止扫描注册 -->
<!-- 自定义命名 -->
<!-- 自定义作用域 -->
<!-- -->
<context:component-scan base-package=""
use-default-filters="false"
name-generator="com.spring.business.HelloWorldService"
scope-resolver="com.spring.business.HelloWorldService"
scoped-proxy="no">
<!-- 包含 --> <context:include-filter type="regex" expression=""/>
<!-- 排除 --> <context:exclude-filter type="annotation" expression=""/> </context:component-scan>
加载资源文件的方法:
<!-- 加载资源文件 --> <context:property-placeholder location="classpath:config.properties"/>
(2) AOP :通过预编译方式(AspectJ)和运行期动态代理(spring Jboss) 实现程序功能的统一维护的一种技术
主要功能:日志记录、性能统计、安全控制、事务处理、异常处理。
<!-- spring aop 配置 -->
<aop:config>
<!-- 声明apsect -->
<aop:aspect id="coveyAspect" ref="aopBean">
<!-- 声明pointcut --> <aop:pointcut id="coveyPointcut" expression="execution(* com.spring.business.AopService.covey())"/>
<!-- 前置通知 --> <aop:before method="coveyBefore" pointcut-ref="coveyPointcut"/>
<!-- 抛出异常通知 --> <aop:after-throwing method="coveyThrowing" pointcut-ref="coveyPointcut"/>
<!-- 返回后通知 --> <aop:after-returning method="coveyReturning" pointcut-ref="coveyPointcut"/>
<!-- 后通知 --> <aop:after method="coveyAfter" pointcut-ref="coveyPointcut"/>
<!-- 环绕通知(没有参数) --> <aop:around method="coveyRound" pointcut-ref="coveyPointcut"/>
<!-- 环绕通知(使用参数) --> <aop:around method="coveyRoundInit" pointcut="execution(* com.spring.business.AopService.coveyInit(String, int)) and args(name, age)"/>
<aop:declare-parents types-matching="匹配的对象" implement-interface="指定接口" default-impl="接口实现类"/> </aop:aspect>
</aop:config>