使用spring的ioc,由spring创建对象
实现步骤:
1.创建maven项目
2.加入maven依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--spring依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
spring的依赖,版本5.5
junit依赖
3.创建类(接口和它的实现类)
和没有使用框架一样,就是普通的类。
//接口
public interface SomeService {
void doSome();
}
//实现类
public class SomeServiceImpl implements SomeService {
@Override
public void doSome() {
System.out.println("执行了SomeServiceImpl的doSome()方法");
}
}
4.创建spring需要使用的配置文件
声明类的信息,这些类由spring创建和管理
IDEA已经为我们设计好了Spring配置文件的模板:
右击resources–>new–>XML configuration file–>Spring Config
模板如下:
<?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">
<!--告诉spring创建对象
声明bean,就是告诉spring要创建某个类的对象
id: 是对象的自定义名称,唯一值。spring通过这个名称找到这个对象
class:类的全限定名称(不能是接口,因为spring是反射机制创建对象,必须使用类)
spring就完成 SomeService someService = new SomeServiceImpl();
spring是把创建好的对象放入到map中,spring框架中有一个map存放对象的。
springMap.put(key(id的值), value(对象))
例如:springMap.put("someService", new SomeService());
一个bean标签声明一个对象。
-->
<bean id="someService" class="com.chen.service.impl.SomeServiceImpl"></bean>
</beans>
<!--
spring的配置文件
1.beans: 是跟标签,spring把java对象称为bean。
2.spring-beans.xsd 是约束文件,和mybatis指定 dtd是一样的。
-->
5.测试spring创建的对象
public class MyTest {
@Test
//不使用spring,由程序员手动创建对象
public void test01() {
SomeService service = new SomeServiceImpl();
service.doSome();
}
@Test
//使用spring创建对象
public void test02() {
//使用spring容器创建的对象
//1.指定spring配置文件的名称
String config = "beans.xml";
//2.创建表示spring容器的对象,ApplicationContext
//ApplicationContext就是表示Spring容器,通过容器对象获取对象
//ClassPathXmlApplicationContext:表示从类路径中加载spring的配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext(config);
//从容器中获取某个对象,要调用某个对象的方法
//getBean("配置文件中的bean的id值")
SomeService someService = (SomeService) ac.getBean("someService");
//使用spring创建好的对象
someService.doSome();
}
}