Spring设计理念
面向Bean的编程 框架的特点:把代码转化为配置文件
Spring两大核心技术:AOP和IOC
Spring的优点
- 低侵入式设计
- 独立于各种应用服务器
- 依赖注入特性将组件关系透明化,降低了耦合度
- 面向切面编程特新允许将通用任务进行集中式处理
- 与第三方框架的良好整合
注入方式
set方法注入
Student类必须有set方法和无参构造方法
<bean id="s" class="com.pojo.Student">
<property name="sutName" value="cuihua"></property>
<property name="age" value="28"></property>
</bean>
public static void main(String[] args){
ApplicationContext ctx = new ClassPathXmlApplication("ApplicationContext.xml");
Student student = ctx.getBean(Student.class);
//如果出现了两个Student类的话,只能根据bean的id来获取
Student student = ctx.getBean("s1");
}
构造方法注入
<bean id="s" class="com.pojo.Student">
<property name="sutName" value="cuihua"></property>
<property name="age" value="28"></property>
</bean>
<bean id="userDao" class="dao.impl.userDaoImpl"/>
<bean id="userService" class="service.impl.UserServiceImpl">
<constructor-arg><ref bean="userDao"/></constructor-arg>
<constructor-arg value="cuihua"></constructor-arg>
<constructor-arg value="18"></constructor-arg>
</bean>
<bean id="s2" class="com.pojo.Student">
<constructor-arg value='cuihua' index="0"></constructor-arg>
<constructor-arg value='98' index="1"></constructor-arg>
<constructor-arg value='18' index="2"></constructor-arg>
</bean>
- 一个<constructor-args>元素表示构造方法的一个参数,且使用时不区分顺序
- 通过<constructor-args>元素的index属性可以指定该参数的位置索引,位置从0开始
- <constructor-args>还提供了type属性用来指定参数的类型,避免字符串和基本数据类型的 混淆
设置注入 | 构造注入 |
通过setter访问器实现 | 通过构造方法实现 |
灵活性好,但setter方法数量较多 | 灵活性差,仅靠重载限制太多 |
时效性差 | 时效性好 |
通过无参构造实例化 | 通过匹配的构造方法实例化,但建议保留无参构造 |
特殊符号的处理:
<bean id="p" class="com.pojo.Person">
<constructor-arg>
<value><![CDATA[&&打算]]></value>
</constructor-arg>
</bean>
需要把value提成是子标签,然后使用<![CDATA[]]>把特殊字符包括起来
p标签
<bean id="s2" class="com.pojo.Student" p:stuName="aa" p:age="18"></bean>
引入外部bean
<bean id="car" class="com.pojo.Car" p:brand="BMW" p:price="400000" p:speed="260"></bean>
<bean id="s" class="com.pojo.Student">
<!--set注入-->
<property name="stuName" value="cc"></property>
<property name="age">
<value>20</value>
</property>
<property name="car" ref="car"></property>
</bean>
内部bean使用得情况比较少
使用注解实现bean的装配
<!--自动扫描使用注解的包-->
<context:component-scan base-package="com.pojo"></context:component-scan>
@Component
public class Student{
public void study(){
System.out.println("学生正在学习");
}
}
props注入
public class DataSource{
private Properties properties;
}//省略setter和getter方法
<bean id="datasource" class="com.pojo.DataSource">
<property name="properties">
<props>
<prop key="driver">com.mysql.jdbc.Driver</prop>
<prop key="url">jdbc:mysql://localhost:3306/stu</prop>
<prop key="username">root</prop>
<prop key="password">123456</prop>
</props>
</property>
</bean>