• 接口调用实现类&& 为什么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
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    求子数组最大和
    layout_weight layout_width = 0dp
    一些日历的实现
    只显示年月日的日历
    每日学习之0512
    git 出现The current branch is not configured for pull No value for key branch.master.merge found in configuration错误的解决办法
    git的配置
    使用Spring security框架实现登陆页面时跳转到favicon.ico问题
    播放视频(c#)
    太阳沉落了
  • 原文地址:https://www.cnblogs.com/theWinter/p/10120725.html
Copyright © 2020-2023  润新知