public interface HelloApi {
public void sayHello();
}
public class HelloImpl implements HelloApi{
public void sayHello() {
System.out.println("Hello World ! ");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- id 表示你这个组件的名字,class表示组件类 -->
<bean id="hello"
class="com.HelloImpl">
</bean>
</beans>
public class HelloImplTest {
@Test
public void testSayHello() {
//ClassPathXmlApplicationContext: ApplicationContext实现,
// 以classes为根目录算起
//1、读取配置文件实例化一个Ioc容器
ApplicationContext context = new ClassPathXmlApplicationContext("helloworld.xml");
//2、从容器获取Bean,注意此处完成 “面向接口编程,而不是面向实现”
HelloApi helloApi = context.getBean("hello",HelloApi.class);
//3、执行业务逻辑
helloApi.sayHello();
//XmlBeanFactory 从classpath 或 文件系统等获取资源(项目根目录)
File file = new File("helloworld.xml");
Resource resource = new FileSystemResource(file);
// = new ClassPathResource("helloworld.xml");
BeanFactory beanFactory = new XmlBeanFactory(resource);
// = new XmlBeanFactory(resource);
HelloApi helloApi2 = (HelloApi)beanFactory.getBean("hello");
helloApi2.sayHello();
// FileSystemXmlApplicationContext:ApplicationContext实现,
// 从文件系统获取配置文件(项目根目录)
BeanFactory beanFactory2 = new FileSystemXmlApplicationContext("helloworld.xml");
HelloApi helloApi3 = (HelloApi)beanFactory2.getBean("hello");
helloApi3.sayHello();
}
}