新人入职,一直在看公司项目代码。今天发现一个对于新人的我来说非常神奇的事情:
项目中声明了一个变量
private AdminService adminService;
而AdminService实际上是一个接口:
public interface AdminService {
Admin queryAdmin(String userName);
}
该接口有一个实现类:
@Service
public class AdminServiceImpl implements AdminService {
public Admin queryAdmin(String userName) {
……
}
}
然而adminService这个引用变量在没有new一个AdminServiceImpl的情况下居然调用了queryAdmin()方法,而运行结果表明调用的是实现类AdminServiceImpl的queryAdmin()方法,这就令我很惊讶:AdminService这个接口是什么时候实例化的?注意到实现类上面的@Service注解,直觉告诉我实例化可能是在配置文件里做的。在初步学习了Spring和@Service相关内容后,写了个类似效果的小例子,以加深理解:实现类Swallow实现接口Bird的fly方法,但是用@Service注解和xml配置文件进行实例化。
软件配置:
- jdk 1.8
- Eclipse
- Spring 4.3.11
代码
Bird接口:
public interface Bird {
public void fly();
}
Swallow实现类:
import org.springframework.stereotype.Service;
@Service
public class Swallow implements Bird{
@Override
public void fly() {
System.out.println("I can fly!!");
}
}
测试函数BirdTest:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class BirdTest {
private static Bird swallow;
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext factory=new ClassPathXmlApplicationContext("BirdBean.xml");
Swallow swallow=(Swallow)factory.getBean("swallow");
swallow.fly();
}
}
BirdBean.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<context:component-scan base-package="d20170918.interfacetest" />
</beans>
项目结构图:(红框部分为本例子相关内容)
运行结果:
九月 18, 2017 5:28:21 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@37f8bb67: startup date [Mon Sep 18 17:28:21 GMT+08:00 2017]; root of context hierarchy
九月 18, 2017 5:28:21 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [BirdBean.xml]
I can fly!!