Spring核心

 一.什么是控制反转

 二.使用Spring IoC的步骤:

1、到入Spring 相关的Jar包(spring-expression,spring-core,spring-context,spring-beans,log4j,commons-logging)

2、编写java类

 1 public class HelloSpring {
 2     // 定义who属性,该属性的值将通过Spring框架进行设置
 3     private String who = null;
 4 
 5     /**
 6      * 定义打印方法,输出一句完整的问候。
 7      */
 8     public void print() {
 9         System.out.println("Hello," + this.getWho() + "!");
10     }
11 
12     /**
13      * 获得 who。
14      * 
15      * @return who
16      */
17     public String getWho() {
18         return who;
19     }
20 
21     /**
22      * 设置 who。
23      * 
24      * @param who
25      */
26     public void setWho(String who) {
27         this.who = who;
28     }
29 
30 }

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的接口

 1 public class HelloSpringTest {
 2 
 3     @Test
 4     public void helloSpring() {
 5         // 通过ClassPathXmlApplicationContext实例化Spring的上下文
 6         ApplicationContext context = new ClassPathXmlApplicationContext(
 7                 "applicationContext.xml");
 8         // 通过ApplicationContext的getBean()方法,根据id来获取bean的实例
 9         HelloSpring helloSpring = (HelloSpring) context.getBean("helloSpring");
10         // 执行print()方法
11         helloSpring.print();
12     }
13 
14 }

三.AOP(面向切面编程)的定义和原理

四.怎样使用AOP

1、增加Spring AOP的Jar文件

2、编写前置增强和后置增强实现日志功能

3、编写配置文件,对业务方法进行增强

4、编写代码获取带有增强处理的业务对象

 

猜你喜欢

转载自www.cnblogs.com/1097123611-abc/p/10385722.html