码迷,mamicode.com
首页 > 编程语言 > 详细

Spring注入

时间:2015-01-08 10:51:24      阅读:309      评论:0      收藏:0      [点我收藏+]

标签:

Spring注入

Spring通过依赖注入这种解耦方式,让Spring的Bean以配置文件组织在一起.

不管是设值注入还是依赖注入,对象都是由spring容器生成

二种注入方式:

设值注入:

<bean id="唯一标识" class="实现类">

  <property name="要注入的属性名" ref="要注入的对象id"/>

</bean>

<bean id="被注入对象的id" class="实现类"></bean>

构造注入:

必须先写一个无参的构造方法,然后构造方法参数必须是属性值,然后bean

<bean id="唯一标识" class="实现类">

  <constructor-org ref="要注入的对象id"/>

</bean>

<bean id="被注入对象的id" class="实现类"></bean>

 

 

附上代码:

public class Chinese implements Person{

private Axe axe;


public Chinese() {}
public Chinese(Axe axe){
this.axe=axe;
}
//构造器注入

//值注入
/* public void setAxe(Axe axe) {
this.axe = axe;
}*/
@Override
public void useAxe() {
System.out.println(axe.chop());
}

}

 

public class SteelAxe implements Axe {

@Override
public String chop() {
return "Steel";
}

}

 

public class StoneAxe implements Axe {

@Override
public String chop() {
return "斧头好慢...";
}

}

 

 

<bean id="personService" class="com.service.PersonService">
<property name="name" value="yinxin"/>
</bean>
<bean id="chinese" class="com.service.impl.Chinese">
<!-- <property name="axe" ref="stoneAxe"/> -->
<constructor-arg ref="steelAxe"/>
</bean>
<bean id="stoneAxe" class="com.service.impl.StoneAxe"/>
<bean id="steelAxe" class="com.service.impl.SteelAxe"/>

public interface Axe {
public String chop();
}

 


public class Chinese implements Person{

private Axe axe;


public Chinese() {}
public Chinese(Axe axe){
this.axe=axe;
}
//构造器注入

//值注入
/* public void setAxe(Axe axe) {
this.axe = axe;
}*/
@Override
public void useAxe() {
System.out.println(axe.chop());
}

}

Spring注入

标签:

原文地址:http://www.cnblogs.com/misyx/p/4210081.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!