1、IOC将控制权转给spring容器,
思路:主动new的地方 => 使用ioc给spring。
入门案例如下:
public interface UserService {
public void addUser();
}
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("a_ioc add user");
}
}
<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">
<!-- 配置service
<bean> 配置需要创建的对象
id :用于之后从spring容器获得实例时使用的
class :需要创建实例的全限定类名
-->
<bean id="userServiceId" class="com.learn.a_ioc.UserServiceImpl"/>
</beans>
@Test
public void demo01(){
//之前开发
UserService userService = new UserServiceImpl();
userService.addUser();
}
@Test
public void demo02(){
//从spring容器获得
//1 获得容器
String xmlPath = "com/learn/a_ioc/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
//2获得内容 --不需要自己new,都是从spring容器获得
UserService userService = (UserService) applicationContext.getBean("userServiceId");
userService.addUser();
}
2. DI 依赖:一个对象需要使用另一个对象, 注入:通过setter方法进行另一个对象实例设置;
思路:首先有两个对象托管给spring,则需要两次的IOC, 两个对象有关系则需要setter连接。
public interface BookDao {
public void save();
}
public class BookDaoImpl implements BookDao {
@Override
public void save() {
System.out.println("di add book");
}
}
public interface BookService {
public abstract void addBook();
}
public class BookServiceImpl implements BookService {
// 方式1:之前,接口=实现类
private BookDao bookDao = new BookDaoImpl();
// 方式2:接口 + setter => 解耦private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
@Override
public void addBook(){
this.bookDao.save();
}
public BookServiceImpl() {
System.out.println("被new 了");
}
}<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">
<!--
模拟spring执行过程
创建service实例:BookService bookService = new BookServiceImpl() IoC <bean>
创建dao实例:BookDao bookDao = new BookDaoImpl() IoC
将dao设置给service:bookService.setBookDao(bookDao); DI <property>
<property> 用于进行属性注入
name: bean的属性名,通过setter方法获得
setBookDao => BookDao => bookDao
ref :另一个bean的id值的引用
-->
<!-- 创建service -->
<bean id="bookServiceId" class="com.learn.b_di.BookServiceImpl" >
<property name="bookDao" ref="bookDaoId"/>
</bean>
<!-- 创建dao实例 -->
<bean id="bookDaoId" class="com.learn.b_di.BookDaoImpl"/>
</beans>