注解开发定义bean @Component
第一步添加扫描组件加载bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 组件扫描加载bean-->
<context:component-scan base-package="com.itheima" />
</beans>
第二步使用@Component定义bean
----1----
@Component("bookDao")
public class BookDaoImpl implements BookDao {
public BookDaoImpl(){
}
public void save() {
System.out.println("book dao save ... ===name===:");
}
}
----2----
@Component
public class BookServiceImpl implements BookService {
private BookDao bookDao = new BookDaoImpl();
public void save() {
System.out.println("book service save ...");
bookDao.save();
}
}
第三步
ApplicationContext cxk = new ClassPathXmlApplicationContext("applicationContext2.xml");
BookDao bookDao = (BookDao) cxk.getBean("bookDao");
BookService bookService = cxk.getBean(BookService.class);
System.out.println(bookDao);
System.out.println(bookService);
总结:
1、Component代替了bean标签
2、Component("这是ID")依旧可以按类型和按ID来匹配bean