1.未使用任何注解
student类
`package com.xie;
public class Student{
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}`
bean.xml文件中的配置如下:
<bean id="student" calss="com.xie.Student">
<property name="id" value="3" />
<property name="name" value="xie" />
</bean>
2.使用@Autowired注解,它主要是对成员变量(嵌套类型的成员变量)进行自动注入。
Teacher类,对student变量使用@Autowired注解
package com.xie;
public class Teacher{
private int age;
@Autowired
private Student student;
}
在bean.xml配置(使用@Autowired注解需要在bean.xml中添加<bean class="org.springframework.beans.factory.annotation.
)
AutowiredAnnotationBeanPostProcessor"/>
<bean name="teacher" class="com.xie.Teacher">
<property name="id" value="6">
<!--student已使用@Autowired注解-->
</bean>
3.使用@component注解,可以完全移除该类在bean.xml的配置
但要在配置文件中加上包扫描<context:component-scan base-package="com.xie"/>
(@component作用其实和@service以及@controller类似,@component是泛化的,当代码有分层的时候@service主要用在service层,@controller主要用在controller层)