spring学习笔记六

一、构造器注入

1.1、BookDao接口和实现类

public interface BookDao {
    void save();
}
public class BookDaoImpl implements BookDao {

    private int connectionNum;
    private String databaseName;

    public BookDaoImpl(int connectionNum, String databaseName) {
        this.connectionNum = connectionNum;
        this.databaseName = databaseName;
    }

    public void save(){
        System.out.println("book dao save......" + databaseName+","+ connectionNum);
    }
}

1.2、BookService接口与实现类

public interface BookService {
    void save();
}
public class BookServiceImpl implements BookService{
    private BookDao bookDao;
    private UserDao userDao;

    public BookServiceImpl(BookDao bookDao,UserDao userDao) {
        this.bookDao = bookDao;
        this.userDao = userDao;
    }

    public void save(){
        bookDao.save();
        userDao.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、总结

  • BookDaoImpl和BookServiceImpl类的构造函数时有参数的,配置文件中添加constructor-arg节点
  • name设置为类中的变量名称,ref是bean的id

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