Spring 能有效地组织 J2EE 应用各层的对象。不管是控制层的 Action 对象,还是业务层的 Service 对象,还是持久层的 DAO 对象,都可在 Spring 的管理下有机地协调、运行。 Spring 将各层的对象以松耦合的方式组织在一起, Action 对象无须关心 Service 对象的具体实现, Service 对象无须关心持久层对象的具体实现,各层对象的调用完全面向接口。当系统需要重构时,代码的改写量将大大减少。
上面所说的一切都得宜于 Spring 的核心机制,依赖注入。依赖注入让 bean 与 bean 之间以配置文件组织在一起,而不是以硬编码的方式耦合在一起。
理解依赖注入 :
依赖注入 (Dependency Injection) 和控制反转 (Inversion of Control) 是同一个概念。具体含义是 : 当某个角色 ( 可能是一个 Java 实例,调用者 ) 需要另一个角色 ( 另一个 Java 实例,被调用者 ) 的协助时,在传统的程序设计过程中,通常由调用者来创建被调用者的实例。但在 Spring 里,创建被调用者的工作不再由调用者来完成,因此称为控制反转 ; 创建被调用者实例的工作通常由 Spring 容器来完成,然后注入调用者,因此也称为依赖注入。
案例:
package cn.csdn.spring;
import java.util.Date;
public class PersonServiceBean {
private String name;
private Integer age;
private Date brith;
//set注入
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public void setBrith(Date brith) {
this.brith = brith;
}
public PersonServiceBean() {
super();
// TODO Auto-generated constructor stub
}
public PersonServiceBean(String name, Integer age, Date brith) {
super();
this.name = name;
this.age = age;
this.brith = brith;
}
@Override
public String toString() {
return "PersonServiceBean [name=" + name + ", age=" + age + ", brith="
+ brith + "]";
}
}
spring容器的配置文件applicationContext.xml
第一种方法:<!-- set方法注入-->
<bean id="personServiceBean" class="cn.csdn.spring.PersonServiceBean">
<!-- 依赖注入的方式 -->
<property name="name"><value>zhangxiaocong</value></property>
<property name="age"><value>33</value></property>
<property name="brith" ref="date"> </property><!-- 出生日期 -->
</bean>
<bean id="date" class="java.util.Date">
<property name="year"><value>97</value></property>
<property name="month"><value>1</value></property>
<property name="date"><value>1</value></property>
</bean>
第二种方法:
<bean id="personServiceBean1" class="cn.csdn.spring.PersonServiceBean">
<!-- 构造器注入:全部都要对象,不能少属性的构造 -->
<constructor-arg index="0">
<value>dfdfdfd</value>
</constructor-arg>
<constructor-arg index="1">
<value>28</value>
</constructor-arg>
<constructor-arg index="2">
<bean class="java.util.Date"></bean>
</constructor-arg>
</bean>
<bean id="personServiceBean" class="cn.csdn.spring.PersonServiceBean">
<!-- 构造器注入:按照类型进行匹配-->
<constructor-arg type="java.lang.String" value="小弟"/>
<constructor-arg type="java.lang.Integer" value="21"/>
<constructor-arg type="java.util.Date" ref="date"/>
</bean>
<bean id="date" class="java.util.Date">
<property name="year"><value>97</value></property>
<property name="month"><value>1</value></property>
<property name="date"><value>1</value></property>
</bean>
读取容器配置文件的方式,个人喜欢第二种
第一种: Resource resource = new ClassPathResource("spring/spring.xml");
BeanFactory bf = new XmlBeanFactory(resource);
第二种: ApplicationContext ac = new ClassPathXmlApplicationContext("spring/Aop.xml");