您的位置:首页 > 编程语言 > Java开发

Spring自动装配(一)autowire=“no”

2011-04-19 20:07 78 查看

在Spring配置文件bean标签中的autowire属性的no参数

指:不适用自动装配,只是用ref进行装配注入


案例:使用autowire=“no”


1、创建类StudentServiceImpl,代码如下:

 

package cn.zd.service;

public class StudentServiceImpl {

private String studentName;

public void setStudentName(String studentName) {
this.studentName = studentName;
}

public String getStudentName() {
return studentName;
}

public void say(){
System.out.println("学生的名字是:"+studentName);
}

}
 


 注意:此类中有一个私有属性studentName,并且必须有这个属性的setter方法


2、创建类TeacherServiceImpl,代码如下:

package cn.zd.service;

public class TeacherServiceImpl {

private String teacherName;

public StudentServiceImpl studentServiceImpl;

public void setTeacherName(String teacherName) {
this.teacherName = teacherName;
}

public void setStudentServiceImpl(StudentServiceImpl studentServiceImpl) {
this.studentServiceImpl = studentServiceImpl;
}

public String getTeacherName() {
return teacherName;
}

public void say(){
System.out.println("老师的名字是:"+teacherName);
System.out.println(teacherName+"老师的学生是:"+studentServiceImpl.getStudentName());
}
}
 

注意:这个类中需要引用StudentServiceImpl 类,并且同样需要有setter方法


3、配置文件applicationContext.xml,内容如下:

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

<bean id="studentServiceImpl" class="cn.zd.service.StudentServiceImpl">
<property name="studentName">
<value>张迪</value>
</property>
</bean>

<!-- TeacherServiceImpl这个类中因为使用了autowire="no"参数,
所以当引用StudentServiceImpl这个类时就要使用ref属性来指明引用的对象-->

<bean id="teacherServiceImpl" class="cn.zd.service.TeacherServiceImpl" autowire="no">
<property name="teacherName">
<value>陈</value>
</property>
<property name="studentServiceImpl">
<ref bean="studentServiceImpl"/>
</property>
</bean>

</beans>
 

 注意:TeacherServiceImpl这个类中因为使用了autowire="no"参数,所以当引用StudentServiceImpl这个类时就要使用ref属性来指明引用的对象,ref中的参数为所引用的对象的id名。


 

4、测试类,代码如下:

package cn.zd.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.zd.service.TeacherServiceImpl;

public class TestNO {

@Test
public void test1(){
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:app*.xml");
TeacherServiceImpl teacherServiceImpl = (TeacherServiceImpl) ac.getBean("teacherServiceImpl");
teacherServiceImpl.say();
}
}
 

  5、运行结果:

老师的名字是:陈 陈老师的学生是:张迪



------------------------------------------------------------

以上为自我理解,若有不足,请高手指点,谢谢.....


 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: