一. 什么是控制反转
二. 使用 Spring IoC 的步骤:
1, 到入 Spring 相关的 Jar 包(spring-expression,spring-core,spring-context,spring-beans,log4j,commons-logging)
2, 编写 java 类
- public class HelloSpring {
- // 定义 who 属性, 该属性的值将通过 Spring 框架进行设置
- private String who = null;
- /**
- * 定义打印方法, 输出一句完整的问候.
- */
- public void print() {
- System.out.println("Hello," + this.getWho() + "!");
- }
- /**
- * 获得 who.
- *
- * @return who
- */
- public String getWho() {
- return who;
- }
- /**
- * 设置 who.
- *
- * @param who
- */
- public void setWho(String who) {
- this.who = who;
- }
- }
3, 编写 Spring 的配置文件 (ApplicationContext.xml) 和编写了 bean
- <?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 元素声明需要 Spring 创建的实例. 该实例的类型通过 class 属性指定, 并通过 id 属性为该实例指定一个名称, 以便在程序中使用 -->
- <bean id="helloSpring" class="cn.springdemo.HelloSpring">
- <!-- property 元素用来为实例的属性赋值, 此处实际是调用 setWho()方法实现赋值操作 -->
- <property name="who">
- <!-- 此处将字符串 "Spring" 赋值给 who 属性 -->
- <value>Spring</value>
- </property>
- </bean>
- </beans>
4, 编写 test 类: 创建 applicationContext 的接口
- public class HelloSpringTest {
- @Test
- public void helloSpring() {
- // 通过 ClassPathXmlApplicationContext 实例化 Spring 的上下文
- ApplicationContext context = new ClassPathXmlApplicationContext(
- "applicationContext.xml");
- // 通过 ApplicationContext 的 getBean()方法, 根据 id 来获取 bean 的实例
- HelloSpring helloSpring = (HelloSpring) context.getBean("helloSpring");
- // 执行 print()方法
- helloSpring.print();
- }
- }
三. AOP(面向切面编程)的定义和原理
四. 怎样使用 AOP
1, 增加 Spring AOP 的 Jar 文件
2, 编写前置增强和后置增强实现日志功能
3, 编写配置文件, 对业务方法进行增强
4, 编写代码获取带有增强处理的业务对象
来源: http://www.jianshu.com/p/4547eb7067ea