Spring容器的xml配置及注解使用

Spring介绍

框架:高度抽取可重用代码的一种设计;高度的通用性;

​ 多个可重用模块的集合,形成某个领域的整体解决方案

Spring框架:容器:可以管理所有的组件;IOC和AOP

IOC(容器):Iversion Of Control 控制反转

用容器来整合框架

控制:资源的获取

  • 主动式(自己用什么资源就创建new)
  • 被动式(资源的获取交给容器创建和设置)

容器:从主动的new资源为被动的接受资源

DI(Dependency Injection):依赖注入(是IOC思想的具体实现)。容器能知道那个组件运行的时候,需要另一个组件,容器通过反射的形式,将容器中的准备好的对象注入(利用反射给属性赋值)到最初的那个组件中。

容器中对象的创建在容器创建的时候就创建了。

一个bean对应一个对象

同一个组件在ioc中是单例的。

javabean的属性名是由getter/setter方法决定的,去掉set之后将首字母小写之后得到的字符串就是属性名。

配置文件:
bean的创建原理

bean的创建就是框架利用反射new出来的bean实例

话说反射是一种效率很低的方法,所以有哪些对象是应该使用bean来创建的呢?

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="stu1" class="com.onezero.Student">
        <property name="name" value="张三"></property>
        <property name="age" value="18"></property>
    </bean>
    <bean id="stu2" class="com.onezero.Student">
        <property name="name" value="李四"></property>
        <property name="age" value="19"></property>
    </bean>
    <bean id="stu3" class="com.onezero.Student">
        <constructor-arg name="age" value="20"></constructor-arg>
        <constructor-arg name="name" value="onezero"></constructor-arg>
    </bean>
    <bean id="stu4" class="com.onezero.Student">
        <constructor-arg value="马云"></constructor-arg>
        <constructor-arg value="40"></constructor-arg>
    </bean>
</beans>

在配置文件中使用property标签是通过set方法来赋值的。通过constructor-arg可以调用有参构造器赋值。若是严格按照有参构造器中参数出现的顺序写属性,则可以省略name。

若没有严格按照构造器中给出的参数数据赋值,可以通过index指定赋给第几个参数。

若是构造器进行了重载且参数个数一样,如果想省略name需要指定type(即参数类型)

综上所述,不省略name是一种比较常见的配置方法。

通过p命名空间为bean赋值

通过get/set方法进行赋值

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="stu05" class="com.onezero.Student" p:age="19" p:name
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值