IOC
IoC容器根据业务需求自动创建对象。
两种方法XML和注解
基于注解
- 配置类。在配置类中写好对象注入到IoC容器以使用。
调用这个IoC里的这个dataConfig对象:
- 扫包+注解。
更简单,不再需要XML和配置类,而是将bean的创建交给目标类,在目标类添加注解来创建。
![[1694332616215.png]]
@Component
注解就代替了上面注解类的代码。想要用的时候先加载IOC容器(context),再扫包,看包里的类有没有这个注解,有的话注入到IoC中。
测试:
AOP
面向切面编程,是一种抽象化的面向对象编程,对面向对象编程的一种补充。
主要应用场景:打印日志,事务,权限管理。
[GroupChat/java/aop]:业务代码和日志打印
耦合度很高,灵活性太差。
前后都打印参数,现在想把重复的代码统一处理。
相同的位置,横切一刀,行成一个水平切面,然后把它抽象成一个对象,重复代码在这里面写。
![[1694333562976.png]]
(如果是函数,需要在业务代码中调用。AOP不需要在业务代码中调用,直接在切面类中配置就可以了)
流程图(一个切面对象只能跟一个实现类生成代理,然后操作代理对象编程)
步骤:
- 创建切片类
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
@Aspect
// 切面类(处理重复的代码, 打印)
public class LoggerAspect {
@Before("execution(public int CalImpl.*(..))")
// 此注解会和CalImpl里所有方法映射,在执行这些方法前执行下面的before方法
public void before(JoinPoint joinPoint){
// Joinpoint 目标方法和切片对象连接起来
String name = joinPoint.getSignature().getName();
System.out.println(name+"方法的参数是" + Arrays.toString(joinPoint.getArgs()));
}
@AfterReturning(value="execution(public int CalImpl.*(..))", returning = "res")
// returning的值会直接映射到Object res
public void afterReturning(JoinPoint joinPoint, Object res){
String name = joinPoint.getSignature().getName();
// joinPoint只能拿到进入方法的时候,方法里面拿不到
System.out.println(name+"方法的参数是" + res);
}
}
- 实现类添加@Component注解
@Component
public class CalImpl implements Cal{
@Override
public int add(int num1, int num2) {
int res = num1 + num2;
return res;
}
@Override
public int sub(int num1, int num2) {
int res = num1 - num2;
return res;
}
@Override
public int mul(int num1, int num2) {
int res = num1 * num2;
return res;
}
@Override
public int div(int num1, int num2) {
int res = num1 / num2;
return res;
}
}
-
配置自动扫包,开启自动生成代理对象
-
使用