Bean
在使用IOC容器之前 ,我们必须了解Spring中Bean的概念是什么。简单来说,Bean就是一个个由IOC容器控制管理的对象,这些Bean一般都是一些类所需要的依赖,从而体现IOC容器的反转控制理念。
IOC容器的使用
- 编写配置文件 applicationContext.xml
<?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:bean的名字 不能重复-->
<!-- class:bean的类型-->
<bean id="bookDao" class="com.wxl.dao.impl.BookDaoImpl"/>
<bean id="bookService" class="com.wxl.service.impl.BookServiceImpl">
<!-- 配置当前bean与其他bean的关系-->
<!-- name:当前bean的某一个属性名-->
<!-- ref:这个属性参照的bean-->
<!-- value:设置基本数据类型使用-->
<property name="bookDao" ref="bookDao"/>
</bean>
</beans>
- 编写测试类来使用IOC容器
public class App {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
BookService bookService = (BookService) ctx.getBean("bookService");
bookService.save();
}
}
运行结果
如此就完成了IOC容器的基本使用。