學生類
@Configuration
public class Student {
@Value("wenhu an")
private String name;
@Value("1602753101")
private String studentId;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", studentId='" + studentId + '\'' +
'}';
}
}
教師類
@Configuration
public class Teacher {
@Value("moqi xu")
private String name;
@Value("111")
private String teacherId;
@Override
public String toString() {
return "Teacher{" +
"name='" + name + '\'' +
", teacherId='" + teacherId + '\'' +
'}';
}
}
課程類
/**
* @author tigerAndBull
* 使用@Component注解標注一個類徒爹,這個類的對象為可被Spring容器注入锈锤,是一個單例的bean
* 注入分為構造器注入和setter注入
* 依賴注入和AOP是Spring的兩大特性
*/
@Component
public class Course {
@Resource
private Student student;
@Resource
private Teacher teacher;
@Override
public String toString() {
return "Course{" +
"學生:" + student.toString() +
", 教師:" + teacher.toString() +
'}';
}
}
Main
/**
* @author tigerAndBull
* 使用@SpringBootApplication注解的類,是啟動主類蹈矮,一般放在項目頂層包下
* 它是一下內(nèi)容的綜合,
* 1 @Configuration 標記一個類來作為bean定義的應用程序上下文的資源
* 2 @EnavleAutoCongfigutation 告訴Spring Boot開始加載基于類路徑下的配置信息,beans褒脯,各種屬性配置
* 3 @ComponententScan 告訴Spring尋找其他組件追他,配置坟募,以及業(yè)務層類岛蚤,最前面才能加載到所有的類
*/
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ApplicationContext ac = SpringApplication.run(DemoApplication.class, args);
Course course = (Course) ac.getBean("course");
System.out.println(course.toString());
}
}
運行結(jié)果
image.png