Spring的基本用法(一)

Spring就是这样一个框架:你可以选择不使用这个框架,但你的开发架构一定会暗合它的思想。

Spring简介

 在Web应用中使用Spring

commons-logging-1.2.jar包也是需要的

 Spring 的核心机制:依赖注入

  1. 设置注入:IOC容器使用属性setter方法来注入被依赖的实例
  2. 构造注入:IOC容器使用构造器来注入被依赖的实例

一、设置注入

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="personService" class="awen.PersonService">
	<property name="name" value="AWen"  />
</bean>
</beans>

  

二、构造注入

构造实例时,已经为其完成了依赖关系的初始化,这种利用构造器来设置依赖关系的方法,称为构造注入

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="personService" class="awen.PersonService">
	<constructor-arg index="0" value="wxc" />
</bean>
</beans>

  

建议采用以设置注入为主,构造注入为辅的注入策略。对于依赖关系无须变化的注入,尽量采用构造注入,而其他的依赖关系的注入,则考虑采用设置注入

原文地址:https://www.cnblogs.com/wxc-kingsley/p/7417945.html