spring学习笔记七

一、自动装配

1.1、BookDao接口和实现类

public interface BookDao {
    void save();
}
public class BookDaoImpl implements BookDao {
    public void save(){
        System.out.println("book dao save......");
    }
}

1.2、BookService接口和实现类

public interface BookService {
    void save();
}
public class BookServiceImpl implements BookService {
    private BookDao bookDao;
    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }
    public void save(){
        bookDao.save();
    }
}

1.3、配置文件



    
    

1.4、使用方法

public static void main(String[] args) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookService bookService = (BookService) ctx.getBean("service");
        bookService.save();
    }

1.5、总结

  • 在配置文件中添加autowire属性为byType
  • spring会按照BookDao类型找到对应的Bean实现注入

你可能感兴趣的:(java,spring,学习,笔记)