实现类:
<pre name="code" class="java"><pre name="code" class="java">package com;
public class UserService {
private String name;
private ByeService byeService ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void SayHello()
{
System.out.println("hello "+this.name);
byeService.SayBye();
}
}
<pre name="code" class="java">package com;
public class ByeService {
private String name ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void SayBye()
{
System.out.println("Bye "+this.name);
}
}
applicationContext.xml文件内容:
<beans>
<bean id="userService" class="com.UserService">
<property name="">
<value></value>
</property>
<property name="byeSerivce" ref="byeService"></property>
</bean>
<bean id="byeSerivce" class="com.ByeService">
<property name="" value=“”>
</property>
</bean>
</beans>
Test调用:
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService us = (UserService)ac.getBean("userService") ;
us.sayHello();
总结:
1. 当ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml")执行时,spring容器对应被创建,同时applicationContext.xml中配置的bean对象就会被创建(内存)
2. spring实际上是一个容器框架,可以配置各种bean,并且可以维护bean与bean之间的关系,当我们需要使用某个bean的时候,我们可以直接getBean(id)只用即可
3. ioc(inverse of control)控制反转:所谓控制反转,就是把创建对象(bean)和维护对象的关系的权利从程序中转移到spring容器(applicationContext.xml)中
4.DI(dependency injection)依赖注入:实际上di和ioc是同一个概念,spring设计者认为di更能表达spring的核心