配置文件:
<!--实验18:使用@Autowried注解实现根据类型实现的自动装配-->
<context:component-scan base-package="com"></context:component-scan>
各层级结构:
package com.atgugui.servlet;
import com.atgugui.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
public class BookServlet {
//自动装配,自动为这个属性赋值
@Autowired
private BookService bookService;
public void doGet(){
bookService.save();
}
}
package com.atgugui.dao;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
/**
* 这个类的id就是默认类名的首字母小写。bookDao就是这个类的id。
* 可以在注解后面写括号,来改组件的名字。
* @Scope(value = "prototype")//修改这个实例为多实例。
*/
//@Repository("bookha")
//@Scope(value = "prototype")
@Repository
public class BookDao {
public void saveBook(){
System.out.println("图书已经被保存!");
}
}
package com.atgugui.service;
import com.atgugui.dao.BookDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
//通过@Service把它加入到容器中
@Service
public class BookService {
@Autowired
private BookDao bookDao;
public void save(){
System.out.println("bookservice--->正在调用dao帮你保存图书...");
bookDao.saveBook();
}
}
测试:
@Test
public void test02(){
BookServlet bookServlet = ioc.getBean(BookServlet.class);
bookServlet.doGet();
}