@Component("bookDao")//此注解代表定义bean,和bean的名字
public class BookDaoImpl implements BookDao {
@Override
public void save() {
System.out.println("book dao save...");
}
}
//扫描bean
<context:component-scan base-package="com"></context:component-scan>
//验证输出
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
BookDao bookDao = (BookDao) ac.getBean("bookDao");
System.out.println(bookDao);
}
--------------------------------------------------------------
@Component//此注解不写名字
public class BookServiceImpl implements BookService {
@Override
public void save() {
System.out.println("book service save...");
}
}
//按类型查找bean
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//按类型查找bean
BookService bookService = ac.getBean(BookService.class);
System.out.println(bookService);
}
//spring提供@Component注解的三个衍生注解
@Repository("bookDao") //表现层
public class BookServiceImpl implements BookService {}
@Service("bookDao") //业务层
public class BookServiceImpl implements BookService {}
@Controller("bookDao") //数据层
public class BookServiceImpl implements BookService {}