Spring test模块

spring提供的基于junit的测试模块,可以简化IOC创建,且可以使用注入
两种方式在spring框架中给类做单元测试
(1)Junit+手动创建IOC容器
(2)Junit+spring test + 自动创建IOC容器+自动注入(不用调用getBean)

junit的版本最少在4.12及以上

pom.xml导入依赖

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.9.RELEASE</version>
</dependency>

加入RunWith注解

@RunWith(SpringJUnit4ClassRunner.class)

Test.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestPersonServiceSpring {
    @Autowired
    IPersonService personService;
    @Autowired
    @Qualifier("personDaoImpl")
    IPersonDao personDao;
    @Test
    public void test01(){
        System.out.println(personService);
        Person person = new Person();
        boolean flag = personService.login(person);
        System.out.println(flag);
    }

Spring AOP

面向切面编程
在不改变方法原代码的基础上,对方法进行功能增强
也就是说生成了一个新的代理类

动态代理

  • JDK动态代理
    Proxy类的静态方法可以创建代理对象
static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)

三个参数

参数1:ClassLoader loader 类加载器 , 用来加载代理对象
参数2:Class<?>[] interfaces 目标类的字节码对象数组. 因为代理的是接口,需要知道接口中所有的方法
参数3:InvocationHandler h 执行句柄, 代理对象处理的核心逻辑就在该接口中
  • 案例

老总类

public class LaoZong implements ILaoZong{
    public void eat(){
        System.out.println("xxx");
        System.out.println("yyyyyy");
    }

}

秘书类

public class MiShu {
    public void smoke(){
        System.out.println("aaaa");
    }
    public void drink(){
        System.out.println("bbbb");
    }
    public void ball(){
        System.out.println("cccc");
    }
}

老总的接口类

public interface ILaoZong {
    void eat();
}

测试类

public class TestLaoZong {
    public static void main(String[] args) {
        final LaoZong laoZong=new LaoZong();
        final MiShu miShu=new MiShu();
        ClassLoader classLoader=LaoZong.class.getClassLoader();
        Class[] interfaces=new Class[]{ILaoZong.class};
        InvocationHandler handler=new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                miShu.smoke();
                Object object=method.invoke(laoZong,args);
                miShu.drink();
                miShu.ball();
                return object;
            }
        };
        ILaoZong iLaoZong= (ILaoZong) Proxy.newProxyInstance(classLoader,interfaces,handler);
        iLaoZong.eat();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值