Spring三种注入方式

spring有三种依赖注入的方式,第一种是构造方法注入

<bean id="bean" class="Test1.Per">
    <constructor-arg name="username" value="xx"></constructor-arg>
    <constructor-arg name="arr">
        <array>
            <value>1</value>
            <value>2</value>
        </array>
    </constructor-arg>
    <constructor-arg name="list">
        <list>
        <value>"xx"</value>
        <value>"cc"</value>
        </list>
    </constructor-arg>
    <constructor-arg name="set">
        <set>
            <value>"ss"</value>
        </set>
    </constructor-arg>
    <constructor-arg name="prop">
        <props>
            <prop key="mmm">"ppp"</prop>
        </props>
    </constructor-arg>
    <constructor-arg name="date" ref="date"></constructor-arg>
</bean>
        <bean id="date" class="java.util.Date" >
          
        </bean>
//bean类

public class Per  {

    private  String username;
    private  int[] arr;
    private List list;
    private Set set;
    private Properties prop;
    private Date date;

    public Per(String username, int[]arr, List list, Set set, Properties prop
    , Date date){
        this.username=username;
        this.arr=arr;
        this.list=list;
        this.set=set;
        this.prop=prop;
        this.date=date;
    }

    public void get(){
       System.out.println(this.list);
       System.out.println(this.arr[0]);
       System.out.println(this.username);
       System.out.println(this.set);
       System.out.println(this.prop);
       System.out.println(this.date);
    }

}

这种方式缺点是在获取bean对象时,注入数据是必须的操作,否则无法创建,即使是无用的数据也要注入。如果有多个构造方法,每个构造方法只有参数的顺序不同,那通过构造方法注入多个参数会注入到第一个出现的构造方法中

第二种方法是setter注入

public class Per  {

    private  String username;

    public void setUsername(String username){
        this.username=username;        
}
    public void get(){

       System.out.println(this.username);

    }

}
<?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:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
    <beans>


<bean id="bean" class="Test1.Per">

    <property name="username" value="pp">
    </property>


     </beans>
      </beans>

最后一种是注解注入,@Resource、@Service、@Controller等

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值