IoC
實(shí)戰(zhàn):依賴注入的例子
消息服務(wù)接口和實(shí)現(xiàn)類
public interface MessageService {
String getMessage();
}
public class MessageServiceImpl implements MessageService {
private String username;
private int age;
public MessageServiceImpl(String username, int age) {
this.username = username;
this.age = age;
}
@Override
public String getMessage() {
return "Hello World!" + "\nusername is " + username + ",age is " + age;
}
}
打印器類
public class MessagePrinter {
final private MessageService messageService;
public MessagePrinter(MessageService messageService) {
this.messageService = messageService;
}
public void printMessage() {
System.out.println(this.messageService.getMessage());
}
}
配置文件
<!--定義bean,并使用構(gòu)造器注入-->
<bean id="messageServiceImpl" class="com.spring.quickstart.MessageServiceImpl">
<constructor-arg name="username" value="Way Lau"/>
<constructor-arg name="age" value="30"/>
</bean>
<bean id="messagePrinter" class="com.spring.quickstart.MessagePrinter">
<constructor-arg name="messageService" ref="messageServiceImpl"/>
</bean>
應(yīng)用主類
public class MessageApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("/applicationContext.xml");
MessagePrinter messagePrinter = context.getBean(MessagePrinter.class);
messagePrinter.printMessage();
}
}
運(yùn)行結(jié)果
Hello worldWay Lau,age is30