Spring日常笔记记录01--第一个例子创建对象
实现步骤:
1.创建maven项目
2.加入maven的依赖
spring的依赖,版本5.2.5
junit依赖
<dependencies> <!--单元测试的依赖--> <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> </dependencies>
3.创建类(接口和他的实现类)
和没有使用框架一样,就是普通的类
package com.example.service; public interface SomeService { void doSome(); }
package com.example.service.impl; import com.example.service.SomeService; public class SomeServiceImpl implements SomeService { @Override public void doSome() { System.out.println("执行了SomeServiceImpl的doSome()的方法"); } }
4.创建spring需要使用的配置文件
声明类的信息,这些类由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"> <!--告诉spring创建对象 声明bean ,就是告诉spring要创建某个类的对象 id:对象的自定义名称,唯一值。spring通过这个名称找到对象 class:类的全限定名称(不能是接口,因为spring是反射机制创建对象,必须使用类) spring就完成 SomeService someService = new SomeServiceImpl(); spring是把创建好的对象放入到map中, spring框架有一个map存放对象的。
springMap.put(id的值,对象); 例如 springMap.put("someService" , new SomeServiceImpl) 一个bean标签只能声明一个对象 --> <bean id="someService" class="com.example.service.impl.SomeServiceImpl"/> </beans> <!-- spring的配置文件 1.beans:是根标签,spring把Java对象成为bean 2.spring-beans.xsd 是约束文件,和mybatis指定 dtd是一样的。 -->
5.测试spring创建的对象
@Test //用实现接口的方法来测试 public void test01(){ SomeService someService = new SomeServiceImpl(); someService.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 service = (SomeService) ac.getBean("someService"); //使用spring创建好的对象 service.doSome(); }