spring基于xml的环境搭建

192 阅读1分钟

spring基于xml的环境搭建

导入坐标

  • 在pom.xml中导入Spring的坐标
<dependency>
	<groupId>org.springfamework</GroupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.2.RELEASE</version>
</dependency>

配置bean对象加入容器

  • 创建spring的配置文件,并导入约束
<?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">        
</beans>
  • 在spring的配置文件中配置bean
<bean id="accountDao" class="com.itcast.dao.AccountDao"/>

<bean id="accountService" class="com.itcast.service.AccountService"/>

在执行方法中获取IOC容器,并获取容器中的对象

  • 获取IOC容器(基于xml配置的方式)
//获取IOC容器,只能读取类路径下的文件
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
  • 另外两种方式:
    • FileSystemXmlApplicationContext:可以读取磁盘所有文件路径下的xml文件(必须有访问权限)
    • AnnotationConfigApplicationContext:代表着注解配置的方式,不读取配置文件
  • 获取容器中的bean对象
AccountService accountService = ac.getBean("accountService",AccountService.class);//获取service

AccountDao accountDao = ac.getBean("accountDao",AccountDao.class);//获取dao