spring学习笔记

 

    <property name="age" value="22"></property>//调用set...()方法
    <property name="name" value="zs"></property>
    <constructor-arg value="WW"></constructor-arg>//调用构造方法
    <constructor-arg value="22"></constructor-arg>

 

//课程接口
public interface ICourse {
   void learn();
}
//java课程
public class JavaCourse implements ICourse{

    @Override
    public void learn() {
        System.out.println("learn java");
    }
}
//html课程
public class HtmlCourse implements ICourse{
    @Override
    public void learn() {
        System.out.println("learn html");
    }
}

 

//学生类
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Student {
    private int stuNo;
    private String stuName;
    private int stuAge;
    public int getStuNo() {
        return stuNo;
    }

    public void setStuNo(int stuNo) {
        this.stuNo = stuNo;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public int getStuAge() {
        return stuAge;
    }

    public void setStuAge(int stuAge) {
        this.stuAge = stuAge;
    }

    @Override
    public String toString() {
        return this.stuNo+","+","+this.stuName+","+this.stuAge;
    }
    public  void learn(String course){
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");//获取IoC容器
         ICourse iCourse =(ICourse)context.getBean(course);//从IoC容器中获取相应的课程
         iCourse.learn();
    }
}

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop   http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">

    <bean id="student" class="Student">
          <property name="stuAge" value="23"></property>
          <property name="stuNo" value="1"></property>
          <property name="stuName" value="zs"></property>
    </bean>
   <bean id="JavaCourse" class="JavaCourse"></bean>
   <bean id="HtmlCourse" class="HtmlCourse"></bean>

 

//测试程序测试
import javafx.application.Application;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import static org.junit.Assert.*;

public class StudentTest {

    @Test
    public void Test() {
//        Student student=new Student();
//        student.setStuNo(1);
//        student.setStuName("zs");
//        student.setStuAge(23);
//        System.out.println(student);
        ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml");
        Student student=(Student)context.getBean("student");
        System.out.println(student);
        student.learn("JavaCourse");
        student.learn("HtmlCourse");

(控制反转)

IOC的集合赋值:

 <bean id="collectionDemo" class="CollectionDemo">
       <property name="list">
           <list>
               <value>football</value>
               <value>basketball</value>
               <value>pingpang</value>
           </list>
       </property>
        <property name="array">
            <array>
            <value>football</value>
            <value>basketball</value>
            <value>pingpang</value>
            </array>
        </property>
        <property name="set">
           <set>
               <value>football</value>
               <value>basketball</value>
               <value>pingpang</value>
           </set>
        </property>
        <property name="map">
            <map>
                <entry>
                    <key>
                        <value>1</value>
                    </key>
                    <value>
                        football
                    </value>
                </entry>
                <entry>
                    <key>
                        <value>2</value>
                    </key>
                    <value>
                        basketball
                    </value>
                </entry>  <entry>
                    <key>
                        <value>3</value>
                    </key>
                    <value>
                        pingpang
                    </value>
                </entry>
            </map>
        </property>
        <property name="properties">
            <props>
                <prop key="1">football</prop>
                <prop key="2">basketball</prop>
                <prop key="3">pingpang</prop>
            </props>
        </property>
    </bean>
 <property name="dataSource" ref="dataSource"></property>//引用变量用ref

通知的三种做法:

//测试代码
import javafx.application.Application;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import static org.junit.Assert.*;

public class StudentTest {

    @Test
    public void Test() {
        IStudentService iStudentService=(IStudentService) 
        context.getBean("studentSeSrvice");
        Student student=(Student)context.getBean("student");
        iStudentService.addStudent(student);
        iStudentService.deleteStudent(1);
    }
}

1.

 (1)通过xml配置:

//通过xml配置的前置通知
import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class LogBefore implements MethodBeforeAdvice {
    @Override
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println("before inform......");
    }
}
//通知xml的后置通知
import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class LogAfter implements AfterReturningAdvice {
    @Override
    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println("After inform");
    }
}
//通过xml配置的异常通知
import org.springframework.aop.ThrowsAdvice;

import java.lang.reflect.Member;

public class AfterThrowing implements ThrowsAdvice {
    public  void afterThrowing(Member method,Object[] args,Object target,Throwable ex){
        System.out.println("异常通知:目标对象:"+target+",方法名:"+method.getName()+",方法参数个数:"+args.length+",异常类型:"+ex.getMessage());
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop   http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
    <aop:config>
        <aop:pointcut id="pointcut1" expression=" execution(public * StudentServiceImpl.*(..))"/>
        <aop:advisor  advice-ref="logBefore" pointcut-ref="pointcut1"></aop:advisor>
    </aop:config>
    <bean id="logAfter" class="LogAfter"></bean>
    <aop:config>
        <aop:pointcut id="pointcut2" expression=" execution(public * StudentServiceImpl.*(..))"/>
        <aop:advisor advice-ref="logAfter" pointcut-ref="pointcut2"></aop:advisor>
    </aop:config>
    <bean id="logException" class="AfterThrowing"></bean>
    <aop:config>
        <aop:pointcut id="pointcut3" expression=" execution(public * StudentServiceImpl.*(..))"/>
        <aop:advisor advice-ref="logException" pointcut-ref="pointcut3"></aop:advisor>
    </aop:config>

结果: 

(2)通知注解通知(xml需要有<aop:aspectj-autoproxy></aop:aspectj-autoproxy>开启注解通知):

package com;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import org.springframework.stereotype.Component;
@Component("logAnnotation")//组件,需要通过xml进行扫描<context:component-scan base-package="com"></context:component-scan>
@Aspect//无@Component时可通过<bean id="id" class="com.LogAspectAnnotation"></bean>直接使用
public class LogAspectAnnotation {
    @Before("execution(public * StudentServiceImpl.*(..))")
    public void myBefore(){
        System.out.println("<注解形式-前置通知>");
    }
    @AfterReturning(pointcut ="execution(public * StudentServiceImpl.*(..))",returning = "returnningValue")
    public void myAfter(JoinPoint jp,Object returnningValue){
        System.out.println("<注解形式-后置通知>:目标对象:"+jp.getTarget()+",方法名:"+jp.getSignature().getName()+",参数表:"+jp.getArgs().length+",返回值:"+returnningValue);
    }
    @AfterThrowing("execution(public * StudentServiceImpl.*(..))")
   public  void myException(){
        System.out.println("<注解形式-异常通知>");
   }

2.通过环绕通知:

(1)通过xml环绕通知:

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class LogAround implements MethodInterceptor {
    Object result=null;
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        try {
            System.out.println("前置通知");
           Object result=methodInvocation.proceed();
            System.out.println("后置通知");
        }catch (Exception e){
            System.out.println("异常通知:目标对象:"+methodInvocation.getThis()+",方法名:"+methodInvocation.getMethod().getName()+",方法参数个数:"+methodInvocation.getArguments().length+",异常类型:"+result);
        }
        return  result;
    }
}

(2)通过注解环绕通知(xml需要有<aop:aspectj-autoproxy></aop:aspectj-autoproxy>开启注解通知):

@Around("execution(public * StudentServiceImpl.*(..))")
   public void myAround(ProceedingJoinPoint jp){
            try{
                System.out.println("<注解形式-前置通知>");
                jp.proceed();
                System.out.println("<注解形式-后置通知>:目标对象:"+jp.getTarget()+",方法名:"+jp.getSignature().getName()+",参数表:"+jp.getArgs().length+",返回值:");
            }catch (Throwable e){
               System.out.println("<注解形式-异常通知>:目标对象:"+jp.getTarget()+",方法名:"+jp.getSignature().getName()+",参数表:"+jp.getArgs().length+",异常信息:"+e.getMessage());
            }finally {
                System.out.println("最终通知。。。");
            }
   }

 结果:

 Schema方式通知:

Spring 开发web项目: 

将通过web.xml中的listener监听tomcat启动时自动实例化IoC容器,通过两种方法告诉监听器listener Ioc容器的位置

(1):xml中context-param声明IOC容器位置,并且application.xml文件放到classpath文件src文件中

 <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

(2)xml中不需要声明IOC容器位置,按默认位置查找IOC容器且名字必须为默认的application.xml,并且application.xml文件放到classpath文件WEB-INF文件中

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值