如果我们按原始的来就会报错如下:
找不到 save 报了空指针
使用依赖注入:自动装配 解决问题
@Autowired: 按类型装配 Spring bean
@SuppressWarnings("all") | |
@Service("bookService") | |
public class BookServiceImpl implements BookService { | |
@Autowired | |
private BookDao bookDao; | |
public void setBookDao(BookDao d){ | |
this.bookDao = d; | |
} | |
public void save(){ | |
System.out.println("BookServiceImpl save rning..."); | |
bookDao.save(); | |
} | |
} |
在 private BookDao bookDao; 上加上注解:@Autowired 注解来进行自动装配
- 测试代码
public void test(){ | |
ApplicationContext c = new AnnotationConfigApplicationContext(SpringConfig.class); | |
BookService service = c.getBean("bookService",BookService.class); | |
service.save(); | |
} |
Run Result
- 可以将 setter 方法给去掉,因为它暴力反射已经帮我们做了
@SuppressWarnings("all") | |
@Service("bookService") | |
public class BookServiceImpl implements BookService { | |
@Autowired | |
private BookDao bookDao; | |
public void save(){ | |
System.out.println("BookServiceImpl save rning..."); | |
bookDao.save(); | |
} | |
} |
Run Result
问题
如果有两个相同的数据层 (Dao), 那么类型就会不一致就会报错如下
BookDaoImpl
@SuppressWarnings("all") | |
@Repository("bookDao") | |
public class BookDaoImpl implements BookDao { | |
public void save(){ | |
System.out.println("BookDaoImpl save rning..."); | |
} | |
} |
- BookDaoImpl1
@SuppressWarnings("all") | |
@Repository("bookDao") | |
public class BookDaoImpl1 implements BookDao { | |
public void save(){ | |
System.out.println("BookDaoImpl save rning..."); | |
} | |
} |
- BookServiceImpl 自动装配类绑定 BookDao 接口类
- 有两个 BookDao 的实现类此时数据就不唯一了,Run 后报错
@SuppressWarnings("all") | |
@Service("bookService") | |
public class BookServiceImpl implements BookService { | |
@Autowired | |
private BookDao bookDao; | |
public void save(){ | |
System.out.println("BookServiceImpl save rning..."); | |
bookDao.save(); | |
} | |
} |
- 解决方式
按名称装配
给 @Repository 注解配置 bean 设置名称
- BookDaoImpl
@SuppressWarnings("all") | |
@Repository("bookDao") | |
public class BookDaoImpl implements BookDao { | |
public void save(){ | |
System.out.println("BookDaoImpl save rning..."); | |
} | |
} |
- BookDaoImpl1
@SuppressWarnings("all") | |
@Repository("bookDao1") | |
public class BookDaoImpl1 implements BookDao { | |
public void save(){ | |
System.out.println("BookDaoImpl save rning... 1"); | |
} | |
} |
- BookServiceImpl
@SuppressWarnings("all") | |
@Service("bookService") | |
public class BookServiceImpl implements BookService { | |
@Autowired | |
private BookDao bookDao; | |
public void save(){ | |
System.out.println("BookServiceImpl save rning..."); | |
bookDao.save(); | |
} | |
} |
- 问题:有两个那么会先执行哪一个呢
- 按顺序执行
Run Result
将注解配置 bean 的名称换下顺序
- BookDaoImpl
@Repository("bookDao1") | |
public class BookDaoImpl implements BookDao { |
- BookDaoImpl1
@Repository("bookDao") | |
public class BookDaoImpl1 implements BookDao { |
Run Result