主要创建的程序如图:
Teacher类: public class Teacher { private int id; private String name; private School school; public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setSchool(School school) { this.school = school; } public int getId() { return id; } public String getName() { return name; } public School getSchool() { return school; } } //最后,通过调用 getter 方法获取 Teacher 的属性,并输出到控制台。
School类:
public class School { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } } TeacherService类:
@Service
public class TeacherService {
@Autowired
private Teacher teacher;
@Autowired
private School school;
public void setTeacherId(int id) {
teacher.setId(id);
}
public void setTeacherName(String name) {
teacher.setName(name);
}
public void setTeacherSchool() {
teacher.setSchool(school);
}
public Teacher getTeacher() {
return teacher;
}
}
AppConfig类:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan(basePackages = "com.example") public class AppConfig { // 使用 @Bean 注解来创建 Teacher 和 School 的实例 @Bean public Teacher teacher() { return new Teacher(); } @Bean public School school() { School school = new School(); school.setName("深圳"); return school; } } 测试Main类: import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); TeacherService teacherService = context.getBean(TeacherService.class); //使用 @Autowired 注解来注入 Teacher 和 School 的实例。 teacherService.setTeacherId(1); teacherService.setTeacherName("小米"); teacherService.setTeacherSchool(); Teacher teacher = teacherService.getTeacher(); System.out.println( teacher.getId()+ teacher.getName()+"is from" + teacher.getSchool().getName()); // System.out.println("Teacher name: " + teacher.getName()); // System.out.println("Teacher school: " + teacher.getSchool().getName()); } } //在 Main 类中,创建一个 Spring 应用程序上下文,并使用 AppConfig 类来配置上下文。
最后的运行结果:
大学生的个人作业,如果大佬看到不完善的地方也可以指出,请不要喷。