Spring依赖注入:基于xml配置
2023-09-14 09:11:44 时间
基础接口 BeanFactory、ApplicationContext。
BeanFactory用于创建并管理、获取各种类的对象。
ApplicationContext从BeanFactory派生而来,并拥有更多实际功能。主要方法是getBean()获取Bean对象。
ApplicationContext可以从类路径加载配置文件(ClassPathXmlApplicationContext),也可以从文件系统中加载配置文件(FileSystemXmlApplicationContext)。
我们可以在xml文件中配置bean,然后通过ApplicationContext接口获取bean实例
Spring能够在applicationContext.xml中通过配置bean完成实例化对象,设置属性等。
1.配置bean
<bean id="dao" class="springTest.DaoImpl">
</bean>
实例化对象,相当于以下代码:
DaoImpl dao=new DaoImpl();
我们可以通过ApplicationContext接口获取对象,如下示:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
DaoImpl dao = (DaoImpl) context.getBean("dao");
ClassPathXmlApplicationContext会读取src文件的下一级中的对应xml文件
2.配置属性property
<bean id="dao" class="springTest.DaoImpl">
<property name="employee" value="lin"></property>
</bean>
设置属性,也就是setter,相当于以下代码:
DaoImpl dao=new DaoImpl();
dao.setEmployee=lin;
3.配置对象属性property
<bean id="dao" class="springTest.DaoImpl"></bean>
<bean id="serviceImpl" class="springTest.ServiceImpl">
<property name="dao" ref="dao"></property>
</bean>
设置对象属性,相当于以下代码:
DaoImpl dao=new DaoImpl();
ServiceImpl serviceImpl=new ServiceImpl();
serviceImpl.setDao=dao;
相关文章
- activiti自定义流程之Spring整合activiti-modeler5.16实例(八):完成个人任务
- spring boot: 一般注入说明(四) Profile配置,Environment环境配置 @Profile注解
- spring属性注入DI
- Spring Boot启动时数据库初始化spring.datasource(转)
- Spring 体系结构详解
- Spring DI依赖注入讲解
- Spring Bean的属性注入
- Spring注解开发-属性依赖注入指定名称的bean
- ABAP模拟Java Spring依赖注入(Dependency injection)的一个尝试
- 解决com.alibaba.fastjson.JSONException: write javaBean error问题以及解决Spring Boot加入Shiro导致spring aop失效的问题
- 1.4Spring 依赖注入(DI)和控制反转(IOC)详解
- Spring的控制反转和依赖注入
- mysql事务级别和spring中应用
- 009-Spring Boot 事件监听、监听器配置与方式、spring、Spring boot内置事件
- Spring IOC源代码具体解释之容器依赖注入
- 理解Spring的Bean工厂
- Spring JDBC入门程序
- JavaEE——Spring学习笔记05【Mybatis的逆行工程】
- JavaEE——Spring学习笔记03【AOP开发】
- 【Spring源码学习】spring IOC容器管理
- 【java】Spring Cloud --Spring Cloud Alibaba 微服务解决方案