1.新建maven项目
修改仓库
按图设置
2.加入依赖,修改pom.xmlspring-context : spring依赖junit:
pom.xml
3.开发人员定义类:接口和实现类类也可以没有接口。org.springframework spring-context5.2.5.RELEASE junit junit4.12 test
接口和实现类定义:和没有spring一样。
DemoService接口
package com.fzf.service;
public interface DemoService {
public void sayHello();
}
package com.fzf.service.impl;
import com.fzf.service.DemoService;
public class DemoServiceImpl implements DemoService {
@Override
public void sayHello() {
System.out.println("hello");
}
}
4.创建spring的配置文件。作用:声明对象。把对象交给spring创建和管理。使用
beans.xml
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;
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.*;
public class MyTest {
@Test
public void test01(){
String config="beans.xml";
ApplicationContext ctx =new ClassPathXmlApplicationContext(config);
DemoService service = ctx.getBean(DemoService.class);
service.sayHello();
}
}



