Spring依赖注入2
接上篇 Spring依赖注入1 Spring依赖注入之xml注入方式
本篇主要讲解基于注解的注入 。
在此之前,大家可以先看一下我写的自动注入有点印象,下文讲解的时候会用到
Spring之自动注入
使用注解注入属性,我们就不需要在xml中进行配置了。
主要工作有两步,1.在类中加入注解。2.在xml总声明扫描器
我们先对简单属性进行赋值,还是熟悉的学生和学校类,
Student类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("studnet")
public class Student {
@Value("Tom")
private String name;
@Value("18")
private int age;
public Student() {
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
这里介绍Component注解标签
@Component 相当于bean 创建类的对象,默认单例
*其中的value 就是bean的id 注解中属性是value 可以隐去不写,而如果你没有设置,则默认是类名的小写
*
在xml文件中进行配置,声明组件扫描器,声明扫描包所在的位置。
<context:component-scan base-package="com.yuyi.service"/>
@Value 是给属性赋值的注解,有两种方式,一种在属性名上直接赋值,一种是在setter方法上面赋值
@Value("Tom")
public void setName(String name) {
this.name = name;
}
@Value("18")
public void setAge(int age) {
this.age = age;
}
运行测试类
两种方法一摸一样!
接下来我们对引用类型进行赋值
引用类型主要是使用自动注入的方式
使用@Autowired
在引用类型的属性名上使用,该注解默认是使用byType的自动注入方式,当扫描器扫描到这里时,会自动按照引用类型的数据类型进行查找,找到School类型进行赋值
School类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("school")
public class School {
@Value("清华大学")
private String name;
@Value("北京")
private String address;
public School() {
}
public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "School{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}
Student类型中添加@Autowired
@Component(value ="student")
public class Student {
private String name;
private int age;
@Autowired
private School school;
运行测试类
我们还可以使用byname的注入方式
在@Autowired下面使用 @Qualifier(“school”)
这样就可以使用按name的方法进行自动注入!
@Autowired
@Qualifier("school")
private School school;
运行结果和上边是一摸一样的,就不贴了哈。
同时,还有一个@Resource注解,和@Autowired差不多,只是默认使用byname注入,如果失败,再使用byType,这个等下次有时间再说哈。