初学spring 对spring的理解不是很深,写个小结 方便大家参考和自己对新知识的认识。写得不好或者有错误,欢迎大家拍砖。学习这东西本来就是要大家一起交流交流的。
下面粘贴下自己的小代码,先简单说下代码的功能。
本文的xml文件全名为 aoplearning.xml
先是在XML中实例化了一个学生类,当然你得先有个学生的java类
package cn.lds.learning.IOC;
public class Student {
private String name;
private String id;
private double height;
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
然后在xml文件中把Student的bean标签加上去
注意property标签
这里我们把学生初始化为 学号为 20111321 身高 169 姓名 xiaoming
<bean id="student" class="cn.lds.learning.IOC.Student" >
<property name="name" value="xiaoming"/>
<property name="id" value="20111321"/>
<property name="height" value="169"/>
</bean>
写个学生活动类StudentAction
package cn.lds.learning.IOC;
public interface StudentAction {
void printAction();
}
package cn.lds.learning.IOC;
public class StudentActionImpl implements StudentAction{
public void printAction() {
// TODO Auto-generated method stub
System.out.println("你可以打篮球咯");
}
}
并在xml文件中加上它的bean标签
<bean id="studentActionImpl" class="cn.lds.learning.IOC.StudentActionImpl"></bean>
现在到了关键位置 要写个AOP的advice了 这里使用的是spring AOP的around Advice看下面代码
package cn.lds.learning.IOC;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class StudentTestInterce implements MethodInterceptor {
/*注意这个方法 它是spring IOC的关键 要有set方法
spring会到xml文件中把实例化后的student这个类注入到里面*/
public void setStudent(Student student) {
this.student = student;
}
public Student student;
public void print() {
System.out.println(student.getName());
}
public Object invoke(MethodInvocation invocation) throws Throwable {
if(student.getHeight()<170){
System.out.println("身高不足 170");
System.out.println("打篮球不很适合哦");
}
if(student.getHeight()>170){
System.out.println("身高标准");
try{
//下面这句是关键哦,around advice可以作为拦截器
return invocation.proceed();
}finally{
System.out.println("打得好不好是你的事情哦");
}
}
return null;
}
}
当然我们得把代理工厂配置上
<!-- 配置代理工厂bean -->
<bean id="studentService"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>cn.lds.learning.IOC.StudentAction</value>
</property>
<property name="target" ref="studentActionImpl"/>
<property name="interceptorNames">
<list>
<value>studentTestInterce</value>
</list>
</property>
</bean>
最后测试下前面的努力
package cn.lds.learning.IOC;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 注入测试
* @author Administrator
*
*/
public class BeanTest {
public static void main(String[] args) {
ApplicationContext ac= new ClassPathXmlApplicationContext("aoplearning.xml");
StudentAction studentTest = (StudentAction)ac.getBean("studentService");
studentTest.printAction();
}
}
运行结果