在Spring框架下实现和调用接口时,不用再代码中创建接口对象。而是依赖容器注入接口的实现对象。
1.创建接口
package service; /**
* Created by xumao on 2016/12/5.
*/
public interface MyService {
public void show();
}
2.接口实现类
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
<?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.测试
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框架下的接口调用成功