一、自动装配
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、配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl" ></bean><bean id="bookService" name="service" class="com.itheima.service.impl.BookServiceImpl" autowire="byType"></bean>
</beans>
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实现注入