依赖注入-setter注入
依赖注入-setter注入
引用类型
-
在bean中定义引用类型属性并提供可访问的set方法
public class BookServiceImpl implements BookService { private BookDao bookDao; private UserDao userDao; @Override public void save() { System.out.println("book service save..."); bookDao.save(); userDao.save(); } public void setBookDao(BookDao bookDao) { this.bookDao = bookDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } }
-
配置中使用property标签ref属性注入引用类型对象
<bean id="bookService" class="com.charley.service.Impl.BookServiceImpl"> <property name="bookDao" ref="bookDao"/> <property name="userDao" ref="userDao"/> </bean>
简单类型
-
在bean中定义简单类型属性并提供可访问的set方法
public class BookDaoImpl implements BookDao { private int connectionNum; private String databaseName; public void setConnectionNum(int connectionNum) { this.connectionNum = connectionNum; } public void setDatabaseName(String databaseName) { this.databaseName = databaseName; } @Override public void save() { System.out.println("book dao save..." + databaseName + "," + connectionNum); } }
-
配置中使用property标签value属性注入简单类型数据
<bean id="bookDao" class="com.charley.dao.impl.BookDaoImpl"> <property name="databaseName" value="mysql"/> <property name="connectionNum" value="10"/> </bean>