spring aop引入功能


spring aop引入功能

       

应用:为已有的类添加新的接口

         

             

                                    

相关注解

         

@DeclareParents

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface DeclareParents {
    String value();    //原有的需要添加接口的实现类(不能是接口,会报错)

    Class defaultImpl() default DeclareParents.class;  //新增接口的实现类
}

        

               

                                    

使用示例

        

                      

         

HelloService

public interface HelloService {

    String hello();
}

       

NewService

public interface NewService {

    String add();
}

         

HelloServiceImpl

@Service
public class HelloServiceImpl implements HelloService {

    @Override
    public String hello() {
        return "hello";
    }
}

        

NewServiceImpl

public class NewServiceImpl implements NewService {

    @Override
    public String add() {
        System.out.println("new service");

        return "new Service";
    }
}

       

CustomAspect

@Aspect
@Component
public class CustomAspect {

    @DeclareParents(value = "com.example.demo.service.impl.HelloServiceImpl",
            defaultImpl = NewServiceImpl.class)   //使用HelloServiceImpl,不可使用HelloService+,会报错
    private NewService newService;
}

                                        

HelloController

@RestController
public class HelloController {

    @Resource
    private HelloService helloService;

    @RequestMapping("/hello")
    public String hello(){
        NewService newService = (NewService) helloService; 
                                //对象helloService引入(实现)了NewService接口,可进行强制类型转换
        return newService.add();
    }
}

         

                

                                    

使用测试

       

localhost:8080/hello,控制台输出:

2022-04-23 21:13:56.788  INFO 2006 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 828 ms
2022-04-23 21:13:57.129  INFO 2006 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-04-23 21:13:57.139  INFO 2006 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 1.505 seconds (JVM running for 1.979)
2022-04-23 21:14:08.743  INFO 2006 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-04-23 21:14:08.743  INFO 2006 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2022-04-23 21:14:08.744  INFO 2006 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
new service

          

                   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值