Spring学习之路第一步 : xml方式实现IOC(控制反转)

最近复习spring,今天开始记录一些小的基础的知识点。供自己回顾加深印象用,希望也能帮到你。首先项目的架构如图:

首先Test类中代码:

private ISchoolSerice ss;

public void test() {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		ss = (ISchoolSerice) context.getBean("ISchoolSerice");
		ss.printName("lisi", "张三");
	
	}

 spring通过Bean标签代替我们new对象,如果类中有上一层的声明,例如:请看SchoolService类。 我们就不需要在类中new,而是在xml中使用

如果在类中有其他类的声明,则可以通过三种方式对其进行注入,而不是在类中new对象。下面是各种方式:

applicationContext.xml中:

<!--方式一:SchoolService中拥有set方法来设置参数  -->
<bean id="ISchoolSerice" class="cn.sdut.service.impl.SchoolService">
<property name="sd" ref="IStudentDao"></property>
<property name="td" ref="ITeacherDao"></property>
</bean>

<bean id="ITeacherDao" class="cn.sdut.dao.impl.TeacherDao"></bean>
<bean id="IStudentDao" class="cn.sdut.dao.impl.StudentDao"></bean>
</beans>
SchoolService代码:
public class SchoolService implements ISchoolSerice{

	private IStudentDao sd ;
	private ITeacherDao td;

	public void setSd(IStudentDao sd) {
		this.sd = sd;
	}

	public void setTd(ITeacherDao td) {
		this.td = td;
	}
	@Override
	public void printName(String studentName, String teacherName) {
		sd.say(studentName);
		td.say(teacherName);
	}

}

applicationContext.xml中:

<bean id="ISchoolSerice" class="cn.sdut.service.impl.SchoolService">
<constructor-arg name="sd" ref="IStudentDao"></constructor-arg>
<constructor-arg name="td" ref="ITeacherDao"></constructor-arg>
</bean>
SchoolService中:

public SchoolService() {
		super();
	}

	public SchoolService(IStudentDao sd, ITeacherDao td) {
		super();
		this.sd = sd;
		this.td = td;
	}
两种方式的在xml中简易写法:

<!--autowire自动装配 byName byType都需要Set方法  constructor需要构造器-->
<bean id="FamilyService" class="cn.sdut.ioc.service.impl.FamilyServiceImpl"
autowire="byName">






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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值