1.初始Spring
spring是一个轻量级框架,他大大简化了java企业级开发,提供了强大,稳定的功能,又没有带来额外的目标
目标: 一是让现有技术更易于实现 二是促进良好的编程习惯
2.Spring IoC
2.1理解"控制反转"
控制反转:也称为依赖注入,是面向对面编程的一种设计理念,用来降低程序代码的耦合度
2.2编写一个Spring程序
(1).编写一个HelloSpring程序
private String who = null;
public String getWho() {
return who;
}
public void setWho(String who) {
this.who = who;
}
public void print() {
System.out.println("Hello," + this.getWho());
}
(2).在项目classpath(src)根目录下创建applicationContext.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-3.2.xsd">
<bean id="helloSpring" class="HelloSprng.HelloSpring">
<property name="who">
<value>Spring</value>
</property>
</bean>
</beans>
(3).添加测试方法
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext1.xml");
HelloSpring helloSpring=(HelloSpring)ctx.getBean("helloSpring");
System.out.println(helloSpring.getName()+helloSpring.getText());
2.3依赖注入
1、设置注入
IoC容器使用setter方法来注入被依赖的实例
2、构造注入
构造实例,完成依赖实例的初始化。
3.Spring AOP(“面向切面编程”)
面向切面编程:简单地说就是在不改变原程序的基础上为代码增加新的功能,对代码进行增强处理。他的设计思想来源于代理设计模式
3.1使用Spring AOP 实现日志输出
(1).导入Spring Aop 相关的jar文件
spring-aop-3.2.13.RELEASE.jar aop实现包
aopallicabe-1.0.jar 依赖包
aspectjweaver-1.6.9.jar 依赖包
(2).编写前置增强和后置增强的实现代码
import java.util.Arrays;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
public class UserServiceLogger {
private static final Logger log = Logger.getLogger(UserServiceLogger.class);
public void before(JoinPoint jp) {
log.info("调用 " + jp.getTarget() + "的" + jp.getSignature().getName()
+ "方法。方法入参" + Arrays.toString(jp.getArgs()));
}
public void afterReturning(JoinPoint jp, Object result) {
log.info("调用 " + jp.getTarget() + "的" + jp.getSignature().getName()
+ "方法.方法返回值" + result);
}
}
getTarget()方法可以得到被代理的目标对象
getSignature()方法返回被代理的目标方法
getArgs()方法返回传递给目标方法的参数数组
(3).编写Spring配置文件,对业务方法进行增强处理
<bean id="theLogger" class="aop.ErrorLogger"></bean>
<aop:config>
<!-- 定义切入点 -->
<aop:pointcut id="pointcut"
expression="execution(public void addNewUser(entity.User))" />
<!-- 引用包含增强方法的Bean -->
<aop:aspect ref="theLogger">
<!-- 将before()方法定义为前置增强并引用pointcut切入点 -->
<aop:before method="before" pointcut-ref="pointcut"></aop:before>
<!-- 将afterReturning()方法定义为后置增强并引用pointcut切入点
通过returning属性指定为名为result的参数注入返回值 -->
<aop:after-returning method="afterReturning"
pointcut-ref="pointcut" returning="result" />
</aop:aspect>
</aop:config>