zoukankan      html  css  js  c++  java
  • 接口调用实现类&& 为什么Autowired定义在接口上

    1、接口与回调

    package edu.cqu.interfaceTest;
    
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Date;
    
    import javax.swing.JOptionPane;
    import javax.swing.Timer;
    
    public class TimeTest  {
        public static void main(String args[]) {
        
            ActionListener listener = new TimePrinter();
            Timer t = new Timer(10000,listener);
            t.start();
            JOptionPane.showMessageDialog(null,"退出程序吗?");
            System.exit(0);
        }
    }
    
    class TimePrinter implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub
            Date now = new Date();
            System.out.println("现在时间时:" + now);
            Toolkit.getDefaultToolkit().beep();
        }
    }

    结果:

    注释:java有函数指针的对应物--Method对象,然后使用起来却比较困难,速度也稍微慢一点,并且在编译时不能提供类型的安全性检查。因此,在任何使用C++函数指针的地方,都应该考虑使用Java中的接口。这就引出下面这个问题。

    2、在SSM项目中,为什么autowired注解在接口上

    // 告诉spring mvc这是一个控制器类

    // 告诉spring mvc这是一个控制器类
    @Controller
    @RequestMapping("")
    public class CategoryController {
        @Autowired
        CategoryService categoryService;
    
        @RequestMapping("listCategory")
        public ModelAndView listCategory(){
            ModelAndView mav = new ModelAndView();
            List<Category> cs= categoryService.list();
    

    @Autowired
    CategoryService categoryService;

    为什么在CategoryController类中 @Auto明明注解在CategoryService 这个接口上 而注入的却是CategoryServiceImpl这个实现类
    因为: (自动装配实现了CategoryService接口的的实例,只有CategoryServiceImpl实现了CategoryService接口,所以就会注入CategoryServiceImpl)

    这种自动装配 @Autowired 还是@Resource在装配或者注入的时候都是先是实例化后再进行的 第一步都是先实例化

    这里他要实例化一个接口是不可能的 所以要找到他的实现类 实例化他的实现类
    ---------------------
    作者:半壁江山009
    来源:CSDN
    原文:https://blog.csdn.net/qq_31963719/article/details/79458002
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    分布式解决方案的收集
    一天带你入门到放弃vue.js(三)
    一天带你入门到放弃vue.js(二)
    一天带你入门到放弃vue.js(一)
    JDK配置环境变量不成功的原因
    蚂蚁课堂(每特学院)-2期
    Java 使用blob对H5视频播放进行加密《java视频加密》
    Java 实现视频下载功能
    高并发与高可用实战之基础知识大型网站架构特征(一)
    Java线程池实现原理之自定义线程池(一)
  • 原文地址:https://www.cnblogs.com/theWinter/p/10120725.html
Copyright © 2011-2022 走看看