在Spring框架下实现和调用接口时,不用再代码中创建接口对象。而是依赖容器注入接口的实现对象。
1.创建接口
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
package service; /** * Created by xumao on 2016/12/5. */ public interface MyService { public void show(); }
2.接口实现类
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
package service.impl; import service.MyService; /** * Created by xumao on 2016/12/5. */ public class MyServiceImpl implements MyService{ @Override public void show() { System.out.println("Spring框架下的接口调用成功"); } }
3.配置文件service.xml
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
<?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"> <bean id="myService" class="service.impl.MyServiceImpl"> </bean> </beans>
4.测试
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
package test; import org.springframework.context.support.ClassPathXmlApplicationContext; import service.MyService; /** * Created by xumao on 2016/12/5. */ public class ServiceTest { public static void main(String arr[]){ MyService myService; ClassPathXmlApplicationContext path=new ClassPathXmlApplicationContext("service.xml"); myService= (MyService) path.getBean("myService"); myService.show(); } }
输出:
Spring框架下的接口调用成功