前面我们把@Autowired注解在类私有变量上,实行了依赖注入。在这篇博客,我们将了解@Autowired的其他使用方式。
我们可以观察@Autowired的元注解:@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})。可以发现该注解还可以注解在构造器、方法和参数变量上。
- 把@Autowired注解在构造器上:
import com.michael.annotation.demo.POJO.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentService {
private Student student;
@Autowired
private StudentService(Student student){
this.student = student;
}
public void showInfo(){
System.out.println(student);
}
}
- 测试代码:
import com.michael.annotation.demo.service.StudentService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import static java.lang.System.out;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
out.println("The container has been initialized.");
((StudentService)applicationContext.getBean("studentService")).showInfo();
out.println("The container has been destroyed.");
}
}
- 输出:
The container has been initialized.
Student{name='Nobody', ID='A00', age=16}
The container has been destroyed.
-
我们可以看到,当@Autowired注解在构造器上,Student Bean仍被注入到了其参数上。其实如果我们把@Autowired去除也同样有该效果。Spring默认组件类(被@Component注解或被其组合注解注解的类,比如@Service和@Repository)只有一个构造函数,并且参数和容器中的Bean可以对应,该Bean就会注入到该参数中。
-
把@Autowired注解到方法上:
import com.michael.annotation.demo.POJO.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentService {
private Student student;
public void showInfo(){
System.out.println(this.student);
}
@Autowired
public void setStudent(Student student){
this.student = student;
}
}
-
重新启动项目,观察输出;发现Student Bean被注入到了方法的参数上。如果该方法被@Bean注解,@Autowired可以被省略。
-
@Autowired可以注解参数,效果仍然一样。