Spring-接口调用

在Spring框架下实现和调用接口时,不用再代码中创建接口对象。而是依赖容器注入接口的实现对象。

1.创建接口

package service;

/**
 * Created by xumao on 2016/12/5.
 */
public interface MyService {
    public void show();
}
View Code

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框架下的接口调用成功");
    }
}
View Code

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>
View Code

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();

    }

}
View Code

 输出:

Spring框架下的接口调用成功

posted @ 2016-12-05 13:49  雨落~无痕  阅读(508)  评论(0编辑  收藏  举报