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();
}
}