首先下载所需的jar包
新建一个工程,创建一个HelloService接口
public interface HelloService {
public void hello();
}
新建一个类HelloServiceImpl实现接口
public class HelloServiceImpl implements HelloService{
public void hello(){
System.out.println("Hello World!");
}
}
新建一个helloworld.xml文件(在src目录下)
<?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表示组件类 -->
<bean id="helloService" class="HelloServicImpl" />
</beans>
现在要实例化一个IOC容器,然后从容器中获取所需的对象,调用接口完成我们的功能。写一个测试类
public class HelloTest {
@Test
public void testHelloWorld() {
// 1、读取配置文件实例化一个IOC容器
ApplicationContext context = new ClassPathXmlApplicationContext("helloworld.xml");
// 2、从容器中获取Bean,注意此处完全“面向接口编程,而不是面向实现”
HelloService helloService = context.getBean("helloService", HelloService.class);
// 3、执行业务逻辑
helloService.hello();
}
getBean里的参数helloService是id,HelloService.class是接口
右键运行JUnit Test,Console成功输出helloworld。