Tedious xml configuration is sometimes annoying, and the annotation configuration supported by Spring simplifies bean configuration.
Therefore, spring can use annotation for active injection and automatic bean detection.
Course class
package com.lubby.test;import org.springframework.stereotype.Component;@Componentpublic class Course {private String courseName = "Enlish";private String teacherName;public Course() {super();}public Course(String courseName, String teacherName) {super();this.courseName = courseName;this.teacherName = teacherName;}public String getCourseName() {return courseName;}public void setCourseName(String courseName) {this.courseName = courseName;}public String getTeacherName() {return teacherName;}public void setTeacherName(String teacherName) {this.teacherName = teacherName;}@Overridepublic String toString() {return "Course [courseName=" + courseName + ", teacherName=" + teacherName + "]";}}
Student Class
package com.lubby.test;import java.util.List;import javax.annotation.Resource;import org.springframework.stereotype.Component;@Componentpublic class Student {private String name;private String school;private int age;@Resource(name = "course")private Course course;private String address;private List
teacherName;public Student() {super();}public Student(String name, String school, int age, Course course, String address, List
teacherName) {super();this.name = name;this.school = school;this.age = age;this.course = course;this.address = address;this.teacherName = teacherName;}public void setAddress(String address) {this.address = address;}public String getAddress() {return address;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSchool() {return school;}public void setSchool(String school) {this.school = school;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Course getCourse() {return course;}public void setCourse(Course course) {this.course = course;}public List
getTeacherName() {return teacherName;}public void setTeacherName(List
teacherName) {this.teacherName = teacherName;}@Overridepublic String toString() {return "Student [name=" + name + ", school=" + school + ", age=" + age + ", course=" + course + ", address="+ address + ", teacherName=" + teacherName + "]";}}
Configuration File
Test class
public class Test {public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("com/lubby/test/test.xml"); Student student = (Student) ctx.getBean("student"); System.out.println(student);}}
Common annotations
@ Component: Spring Component
@ Controller: the controller in SpringMVC
@ Service indicates the Service in SpringMVC
Generally, @ Componen is used to mark any custom annotation.
@ Resource (name = "course") is used to inject bean objects according to name by default. If no name is specified, the default name is the first letter of the class in lowercase.