Spring一共有几种注入方式

tim-qtp...小于 1 分钟Spring框架

  1. 构造函数注入:通过类的构造函数将依赖对象传入。

    @Component
    public class ExampleService {
        private final Dependency dependency;
    
        @Autowired
        public ExampleService(Dependency dependency) {
            this.dependency = dependency;
        }
    
        // 其他方法
    }
    
  2. Setter 方法注入:通过 Setter 方法为类的成员变量设置依赖对象。

    @Component
    public class ExampleService {
        private Dependency dependency;
    
        @Autowired
        public void setDependency(Dependency dependency) {
            this.dependency = dependency;
        }
    
        // 其他方法
    }
    
  3. 字段注入:直接在类的成员变量上使用 @Autowired 注解,Spring 会自动注入依赖对象。

    @Component
    public class ExampleService {
        @Autowired
        private Dependency dependency;
    
        // 其他方法
    }