标签:spring ioc helloworld 依赖注入 反转控制
package cn.dennishucd;
public interface MessageService {
public String getMessage();
}package cn.dennishucd;
public class MessageServiceImpl implements MessageService {
@Override
public String getMessage() {
return "Hello World!";
}
}package cn.dennishucd;
public class MessagePrinter {
final private MessageService service;
public MessagePrinter(MessageService service) {
this.service = service;
}
public void printMessage() {
System.out.println(this.service.getMessage());
}
}package cn.dennishucd;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloworldSpring {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("helloworld.xml");
MessagePrinter printer = (MessagePrinter) context.getBean("printer");
printer.printMessage();
((ClassPathXmlApplicationContext)context).close();
}
}<?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: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">
<bean id="service" class="cn.dennishucd.MessageServiceImpl"/>
<bean id="printer" class="cn.dennishucd.MessagePrinter">
<constructor-arg ref="service"/>
</bean>
</beans>Helloworld之Spring依赖注入/控制反转(DI/IoC)版
标签:spring ioc helloworld 依赖注入 反转控制
原文地址:http://blog.csdn.net/gobitan/article/details/40584031