最近复习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">