理解IOC
IOC定义
控制反转IOC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IOC的一种方法;我们在代码中使用new来创建对象,对象的创建与对象的关系耦合度很高;如果交由第三方去创建和管理对象则视为控制反转;
以上的定义描述仍然很抽象,下面来了解一下IOC存在的意义。
如果不存在IOC我们的代码组成
定义一个接口A,实现接口A的类AImpl,定义一个service接口,定义一个ServiceImpl类实现Service.在ServiceImpl中调用A中的方法。
public interface A {
public void getA();
}
public class AImpl implements A {
public void getA() {
System.out.println("执行A");
}
}
public interface Service {
public void getService();
}
public class ServiceImpl implements Service{
private A a = new AImpl();//创建对象
public void getService() {
a.getA();
}
}
//测试方法
public class IocTest1 {
@Test
public void test() {
Service service = new ServiceImpl();
service.getService();
}
}
仔细想一下,如果A的实现类比较多,要根据不同的场景使用不通的实现类的方法,例如
public class BImpl implements A {
public void getA() {
System.out.println("B的实现类");
}
}
public class ServiceImpl implements Service{
private A a = new BImpl ();//创建对象,此处需要修改为BImpl
public void getService() {
a.getA();
}
}
假如 创建A对象的地方比较多,如果A的实现类发生了改变,那么所有的创建对象的地方都要修改,这样是不合理的
所以有了IOC的概念
public class IocServiceImpl implements Service{
private A a;
public void setA(A a) {
this.a = a;
}
public void getService() {
a.getA();
}
}
@Test
public void iocTest() {
IocServiceImpl service = new IocServiceImpl();
service.setA(new AImpl());//此处创建对象
service.getService();
}
此处以不难发现,对象是谁调用谁创建,是由调用者控制的,降低了耦合度;此处便是IOC的意义
在这里只介绍注解的方式进行bean的注入,xml配置的方式读者可以去官网了解,实际项目中现在主要以注解的方式;
注解实现bean 的自动装配
@Component("user")//注解注入bean
public class User {
public String name;
@Value("默认值")//默认值
public void setName(String name) {
this.name = name;
}
}
@Controller、@Service、@Repository 与@Component注解的功能是一样的,只用于不同的场景,方便代码分层:实际项目中 Controller层 用@Controller 注解;Service层用@Service 注解;Dao层用@Repository注解;配置上这些注解Spring会在上下文中为某个bean寻找依赖的bean
使用java类配置bean的装配
public class User {
public String name = "it小王子";
}
@Configuration//标注这是一个配置类
public class Conficuration {
@Bean("user")//注入bean bean的名称为user
public User getUser() {
return new User();
}
}
//测试
public class BeanTest {
@Test
public void beanTest1() {
ApplicationContext application = new
AnnotationConfigApplicationContext(Conficuration.class);
User user = (User)
application.getBean("user"); System.out.println(user.name);
}
}
理解AOP(Aspect Oriented Programming)
aop的定义:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的同意维护的一种技术。
从定义中也可以看出,aop的底层也就是 代理模式的体现
了解一下代理模式
//静态代理
public interface UserInterface {
//定义一个接口实现增删该查的功能
public void insert();
public void delete();
public void update();
public void query();
}
public class UserImpl implements UserInterface {
public void insert() {
System.out.println("插入一条数据");
}
public void delete() {
System.out.println("删除一条数据");
}
public void update() {
System.out.println("更新一条数据");
}
public void query() {
System.out.println("查询数据");
}
}
//代理类
public class UserPorxy implements UserInterface{
private UserImpl userImpl;
public void setUserImpl(UserImpl userImpl) {
this.userImpl = userImpl;
}
public void insert() {
System.out.println("此处可以做任何事情,比如添加日志");
userImpl.insert();
}
public void delete() {
System.out.println("此处可以做任何事情,比如添加日志");
userImpl.delete();
}
public void update() {
System.out.println("此处可以做任何事情,比如添加日志");
userImpl.update();
}
public void query() {
System.out.println("此处可以做任何事情,比如添加日志");
userImpl.query();
}
}
//使用代理
public class UserProxyTest1 {
@Test
public void userProxyTest1() {
UserImpl impl = new UserImpl();
UserPorxy userporxy = new UserPorxy();
userporxy.setUserImpl(impl);
userporxy.delete();
}
}
//动态代理–jdk动态代理
public interface UserInterface {
//定义一个接口实现增删该查的功能
public void insert();
public void delete();
public void update();
public void query();
}
public class ProxyHandler implements InvocationHandler{
private UserInterface userInterface;
public void setUserInterface(UserInterface userInterface) {
this.userInterface = userInterface;
}
//生成代理类
public Object getProxy() {
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
userInterface.getClass().getInterfaces(),this);
}
//处理代理实例上的方法
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("调用方法之前做什么");
Object result = method.invoke(userInterface, args);
System.out.println("调用方法之后做什么");
return result;
}
}
@Test
public void userProxyTest2() {
UserImpl impl = new UserImpl();
ProxyHandler handler = new ProxyHandler();
handler.setUserInterface(impl);
UserInterface userInterface = (UserInterface) handler.getProxy();
userInterface.delete();
}
Spring中Aop的应用场景
我在项目中真是使用过的Aop如开发完成后 用户要求要在每次操作过程中(新增、修改、删除)的地方添加日志;统一做文件导出处理等,所以Aop在实际项目中还是很重要的;
由于本人使用Aop是基于Springboot的所以此处给与spring boot应用Aop的demo
自定义注解实现AOP
//定义注解
package com.example.demo.controller;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface OperationLog {
//这两个参数完全是为了告诉读者如何获取注解中的参数
//方法描述
String detail() default "";
//日志等级
int level() default 0;
}
package com.example.demo.controller;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
//定义切面
@Aspect
@Component
public class LogAspect {
//使用注解方式定义切点
@Pointcut("@annotation(com.example.demo.controller.OperationLog)")
public void operationLog() {};
//环绕通知 相当于 MethodInterceptor
@Around("operationLog()")
public Object doAround(ProceedingJoinPoint joinPoint) {
Object res = null;
long time = System.currentTimeMillis();
try {
MethodSignature signature = (MethodSignature)joinPoint.getSignature();
OperationLog annotation = signature.getMethod().getAnnotation(OperationLog.class);
System.out.println("注解属性:"+annotation.detail());
System.out.println("注解属性:"+annotation.level());
res = joinPoint.proceed();
time = System.currentTimeMillis() - time;
} catch (Throwable e) {
e.printStackTrace();
}finally {
System.out.println("添加操作日志");
}
return res;
}
@Before("operationLog()")
public void doBeforeAdvice(JoinPoint joinPoint) {
System.out.println("执行方法前todo");
}
//处理完请求返回内容
@AfterReturning(returning = "ret",pointcut = "operationLog()")
public void doAfterReturning (Object ret) {
System.out.println("方法的返回值 : " + ret);
}
//方法异常时执行
@AfterThrowing("operationLog()")
public void throwss(JoinPoint jp){
System.out.println("方法异常时执行.....");
}
/**
* 后置最终通知,final增强,不管是抛出异常或者正常退出都会执行
*/
@After("operationLog()")
public void after(JoinPoint jp){
System.out.println("方法最后执行.....");
}
}
@Controller
@RequestMapping("user")
public class UserController {
@ResponseBody
@RequestMapping("/testAop")
@OperationLog(detail = "描述测试",level = 2)
public String testAop() {
return "测试成功";
}
}
application配置文件中要添加
spring.aop.auto=true #开启aop配置
pom中需要引用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
//启动服务页面调用即可看到日志
http://127.0.0.1:8080/user/testAop
注解属性:描述测试
注解属性:2
执行方法前todo
添加操作日志
方法最后执行.....
方法的返回值 : 测试成功
完结