由之前的IoC可以知道,我们写在具体对象后面的new方法肯定不能要了,这时候就要通过依赖注入的形式将Dao配置到Service中
Dependence Import的步骤如下:
1. 在Service类中给Dao提供setter方法
原本我们是直接给bookDao
new了一个对象
public class BookServiceImpl implements BookService {
private BookDao bookDao = new BookDaoImpl();
public void save(){
System.out.println("book service save...");
bookDao.save();
}
}
修改如下,给bookDao设置一个set方法(在IDEA中在bookDao上按Alt+Insert可以快速生成set方法)
public class BookServiceImpl implements BookService {
// 第一步:删除原本的new方法,给bookDao设置一个setter方法
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
private BookDao bookDao;
public void save(){
System.out.println("book service save...");
bookDao.save();
}
}
<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.example.demo231116.dao.impl.BookDaoImpl" />
<bean id="bookService" class="com.example.demo231116.service.impl.BookServiceImpl">
<property name="bookDao" ref="bookDao"/>
bean>
beans>
我们要在bookService中配置bookDao这个对象(name),参考的是id为bookDao的bean(ref)。
结果如下:
######################
完整代码:
package com.example.demo231116.dao;
public interface BookDao {
void save();
}
BookDaoImplt.java:
package com.example.demo231116.dao.impl;
import com.example.demo231116.dao.BookDao;
public class BookDaoImpl implements BookDao {
public void save(){
System.out.println("book dao save...");
}
}
BookService.java:
package com.example.demo231116.service;
public interface BookService {
void save();
}
BookServiceImplt.java:
package com.example.demo231116.service.impl;
import com.example.demo231116.dao.BookDao;
import com.example.demo231116.dao.impl.BookDaoImpl;
import com.example.demo231116.service.BookService;
public class BookServiceImpl implements BookService {
// 5. 删除使用new建立对象,
// 6. 同时建立set方法
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
private BookDao bookDao;
public void save(){
System.out.println("book service save...");
bookDao.save();
}
}
Deomo231116Application.java:
package com.example.demo231116;
import com.example.demo231116.service.BookService;
import com.example.demo231116.service.impl.BookServiceImpl;
public class Demo231116Application {
public static void main(String[] args) {
BookService bookService = new BookServiceImpl();
bookService.save();
}
}
applicationcontext.xml:
<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.example.demo231116.dao.impl.BookDaoImpl" />
<bean id="bookService" class="com.example.demo231116.service.impl.BookServiceImpl">
<property name="bookDao" ref="bookDao"/>
bean>
beans>