Spring(四)注解
@Component 表示一个类是被Spring容器管理的一个Bean
@Value 表示给类的普通属性赋值
@Resource 给类的域属性赋值
@autoWire 给类的域属性赋值
后面两个的作用相同,但是他们来源的包不同
Resource是JDK提供的注解 import javax.annotation.Resource;
Spring提供的注解import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
那么怎么使用注解给类中的属性赋值呢
@Component("stu")
public class Student {
@Value("wb")
private String name;
@Value("20")
private String age;
@Resource(name = "car")
//@Autowired
//@Qualifier(value = "car")
private Car car;
public Car getCar() {
return car;
} public void setCar(Car car) {
this.car = car;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
@Component("car")
public class Car {
@Value("black")
private String color;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="cn.Spring.t06annotationdi"></context:component-scan>
@Test
public void t2(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext05annotationdi.xml");
Student stu= (Student) context.getBean("stu");
System.out.println(stu.getName());
System.out.println(stu.getAge());
System.out.println(stu.getCar().getColor());
}