👍自动装配方式
- IoC容器根据bean所依赖的资源在容器中自动查找并注入到bean中的过程称为自动装配
自动装配方式
- 按类型(常用)
- 按名称
- 按构造方法
- 不启用自动装配
👍案例
👍BookDao接口
package com.study.dao;
public interface BookDao {
void save();
}
👍BookDaoImpl实现类
package com.study.dao.impl;
import com.study.dao.BookDao;
public class BookDaoImpl implements BookDao {
public void save() {
System.out.println("BookDaoImpl...");
}
}
👍BookService接口
package com.study.service;
public interface BookService {
void save();
}
👍BookServiceImpl实现类
package com.study.service.impl;
import com.study.dao.BookDao;
import com.study.service.BookService;
public class BookServiceImpl implements BookService {
private BookDao bookDao;
public void save() {
bookDao.save();
System.out.println("BookServiceImpl...");
}
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
}
👍applicationContext.xml配置文件
注意:
- 第一种按类型autowire="byType",id="bookDao" 则可以不写
- 第二种按名称autowire="byName",如果id="bookDao1",则报错
<?xml version="1.0" encoding="UTF-8"?>
<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.study.dao.impl.BookDaoImpl"></bean>
<bean id="bookService" class="com.study.service.impl.BookServiceImpl" autowire="byType">
</bean>
<!-- 第一种按类型autowire="byType",id="bookDao" 则可以不写-->
<!-- 第二种按名称autowire="byName",如果id="bookDao1",则报错-->
</beans>
👍Test测试类
import com.study.dao.BookDao;
import com.study.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
BookService service = app.getBean(BookService.class);
service.save();
}
}
/*
BookDaoImpl...
BookServiceImpl...
*/