私とSpring 3を学んでノート1を学びます
2458 ワード
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();
}
}