IOC和AOP使用扩展

1.构造注入

Spring提供了多种依赖注入的手段,除了通过属性的setter访问器,还可以通过带参构造方法实现依赖注入

注入Bean属性---构造注入配置方案

Spring配置文件中通过<constructor-arg>元素为构造方法传参

注意:

1、一个<constructor-arg>元素表示构造方法的一个参数,且使用时不区分顺序。

2、通过<constructor-arg>元素的index 属性可以指定该参数的位置索引,位置从0 开始。

3、<constructor-arg>元素还提供了type 属性用来指定参数的类型,避免字符串和基本数据类型的混淆。

在实体类中声明一个带参的构造

public HappyService(String info, Integer age) {
        this.info = info;
        this.age = age;
    }

在xml文件中用构造注入的方式赋值

 <!--构造赋值-->
             <bean id="service" class="happy.HappyService">
           <constructor-arg index="0" value="周永琪"></constructor-arg>
                <constructor-arg index="1" value="18"></constructor-arg>
            </bean>

使用p命名空间注入属性值

1.创建实体类

public class Student {
    private  String name;
    private Integer age;

    private Car car;

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {

        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

2.xml节点中赋值

 xmlns:p="http://www.springframework.org/schema/p"    引入P标签
<!--
P命名空间赋值
-->
  <bean id="Student" class="happy.Student" p:name="张毅" p:age="18" p:car-ref="cars">
  </bean>
<bean id="cars" class="happy.Car">
    <property name="color" value="蓝色"></property>
    <property name="brand" value="布加迪威龙"></property>
</bean>

注入不同数据类型  list,Set,Map,Properties,String[]

    public String[] array;
    public List<String> list;
    public Set<String> set;
    public Map<String,String> map;

    public Properties properties;
<bean  id="mycollection" class="MyCollection.collection" scope="prototype">
    <property name="array">
        <array>
            <value>青鸟杯</value>
            <value>世界杯</value>
            <value>苹果派</value>
        </array>
    </property>

    <property name="list">
    <list>
        <value>程序员</value>
        <value>分析师</value>
        <value>架构师</value>
    </list>
</property>

    <property name="set">
        <set>
            <value>李白</value>
            <value>韩信</value>
            <value>妲己</value>
        </set>
    </property>

    <property name="map">
        <map>
        <entry key="Y2167">
            <value>面试题</value>
        </entry>
            <entry key="Y2166">
                <value>青鸟杯</value>
            </entry>
            <entry key="S2229">
                <value>多线程</value>
            </entry>
        </map>
    </property>

    <property name="properties">
        <props>
            <prop key="1">第一名</prop>
            <prop key="2">第二名</prop>
            <prop key="3">第三名</prop>
        </props>
    </property>
</bean>

 

原文地址:https://www.cnblogs.com/1234AAA/p/8510496.html