实现步骤:
工程大概结构:
1.新建maven项目
修改仓库
按图设置
2.加入依赖,修改pom.xml
spring-context :
spring依赖junit:
pom.xml
<dependencies>
<!--spring依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
3.开发人员定义类:接口和实现类类也可以没有接口。
接口和实现类定义:和没有spring一样。
DemoService接口
package com.fzf.service;
public interface DemoService {
public void sayHello();
}
package com.fzf.service.impl;
import com.fzf.service.DemoService;
/**
* @author:FZF
* @Data:2022/6/3 16:21
* @Function:
*/
public class DemoServiceImpl implements DemoService {
@Override
public void sayHello() {
System.out.println("hello");
}
}
4.创建spring的配置文件。作用:声明对象。把对象交给spring创建和管理。
使用<bean>表示对象声明,一个bean表示一个java对象。
beans.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">
<!--声明对象
id:自定义对象名称,唯一值。
class:类的全限定名称,spring通过反射机制创建对象,不能是接口
spring根据id, class创建对象,把对象放入到spring的一个map对象。
map.put(id,对象)
-->
<bean id="demoService" class="com.fzf.service.impl.DemoServiceImpl"/>
</beans>
5.使用容器中的对象。
创建一个表示spring容器的对象 Applicationcontext从容器中,根据名称获取对象,使用getBean("对象名称")
DemoMain
package com.fzf;
import com.fzf.service.DemoService;
import com.fzf.service.impl.DemoServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author:FZF
* @Data:2022/6/3 16:22
* @Function:
*/
public class DemoMain {
public static void main(String[] args) {
//未使用spring管理对象前
//DemoService demoService=new DemoServiceImpl();
//demoService.sayHello();
//使用spring管理
//1.指定spring配置文件:从类路径(classspath)之下开始的路径
String config="beans.xml";
//2.创建容器对象,ApplicationContext表示spring容器对象。通过ctx获取java对象
ApplicationContext ctx=new ClassPathXmlApplicationContext(config);
//3.从容器中获取指定名称的对象,使用getBean("id")
DemoService demoService = (DemoService) ctx.getBean("demoService");
//4.调用对象的方法,接口中的方法
demoService.sayHello();
}
}
MyTest:测试类
package com.fzf;
import com.fzf.service.DemoService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.swing.*;
/**
* @author:FZF
* @Data:2022/6/3 16:54
* @Function:
*/
public class MyTest {
@Test
public void test01(){
String config="beans.xml";
ApplicationContext ctx =new ClassPathXmlApplicationContext(config);
DemoService service = ctx.getBean(DemoService.class);
service.sayHello();
}
}