注: 这一章不需要建Web项目
1。怎样做依赖注入?
a.加入包,注:依赖注入只加入一个Spring Core这个核心包就好了。AOP则要加入AOP包
b.由于代码较多,就只列一个包资源管理器的图看一下吧
c.配置时应该这样配置:
<bean id="colorInk" class="com.yenange.entity.ColorInk"> </bean>
<bean id="blackInk" class="com.yenange.entity.BlackInk"> </bean>
<bean id="a4paper" class="com.yenange.entity.A4paper"> </bean>
<bean id="b5paper" class="com.yenange.entity.B5paper"> </bean>
<bean id="printer" class="com.yenange.entity.Printer">
<property name="ink" ref="blackInk"></property>
<property name="paper" ref="b5paper"></property>
</bean>
规律:
1、实现类:在bean里面直接配就好了;相当于:
ColorInk colorInk=new ColorInk();//……
2、普通类中的接口属性
id和class是同上面,
属性如果是普通的字段,如String,int 类型等,用value=”……”就好了;
属性如果是接口或类,则ref=”……”
注:要用到依赖注入,则属性一定要有setter方法,否则不行。
d.做测试:
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
Printer p=(Printer)context.getBean("printer");
p.print("红色","b5","打印内容测试");
对于Spring来说,这应该是最简单的部分了吧。
2.怎么样配置AOP?
a. 加入Spring AOP包;上面有图;
b. 要拦截方法,那这个方法必定在一个类中,但是:这个类必须实现一个接口,Spring才能拦截。
c. 拦截了方法, 总得做什么事吧,这个事就是通知:Advice, 分前置通知、后置通知、环绕通知、异常通知。通知也要建立一个类,类里面有一个继承好的方法。
d. 上一些代码,好看一点吧。
想拦截的方法:
package com.yenange.biz;
public class Teacher implements ITeacher {
public void giveLessson(String teacher, String content) {
System.out.println(teacher+"开始上课,内容:"+content);
}
}
它实现这个接口:
package com.yenange.biz;
public interface ITeacher {
public void giveLessson(String teacher,String content);
}
拦截后要做的事:通知
package com.yenange.biz;
import java.lang.reflect.Method;
import java.util.Date;
import org.springframework.aop.MethodBeforeAdvice;
public class DianMingAdvice implements MethodBeforeAdvice {
/**
* method:被拦截的方法
* arg1:被拦截方法的参数
* target:被拦截的对象---当前就是Teacher这个类
*/
public void before(Method method, Object[] arg1, Object target)
throws Throwable {
System.out.println("时间"+new Date());
System.out.println("调用了"+method.getName());
System.out.println("参数为:");
for (int i = 0; i < arg1.length; i++) {
Object obj=arg1[i];
System.out.println("参数:"+(i+1)+"为:"+obj);
}
System.out.println("上课之前要先点名!");
}
}
e. 怎么样配置aop.xml?
<bean id="teacher" class="com.yenange.biz.Teacher"></bean>
<bean id="xiaoye" class="com.yenange.biz.DianMingAdvice"></bean>
<bean id="teacher2" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.yenange.biz.ITeacher</value>
</property>
<!-- 拦截 -->
<property name="interceptorNames">
<list>
<value>xiaoye</value>
</list>
</property>
<property name="target" ref="teacher"></property>
</bean>
规律:
f.测试:
ApplicationContext context=new ClassPathXmlApplicationContext("aop.xml");
ITeacher t=(ITeacher)context.getBean("teacher2");
t.giveLessson("老何", "java");
注意:要用接口去接收!
不是太难,只是难记。