Spring inject without autowire annotation

前端 未结 2 1085
轻奢々
轻奢々 2020-12-30 06:58

I find some answer: https://stackoverflow.com/a/21218921/2754014 about Dependency Injection. There isn\'t any annotation like @Autowired, @Inject o

2条回答
  •  爱一瞬间的悲伤
    2020-12-30 07:45

    Yes, example is correct (starting from Spring 4.3 release). According to the documentation (this for ex), if a bean has single constructor, @Autowired annotation can be omitted.

    But there are several nuances:

    1. When single constructor is present and setter is marked with @Autowired annotation, than both constructor & setter injection will be performed one after another:

    @Component
    public class TwoInjectionStyles {
        private Foo foo;
    
        public TwoInjectionStyles(Foo f) {
            this.foo = f; //Called firstly
        }
    
        @Autowired
        public void setFoo(Foo f) { 
            this.foo = f; //Called secondly
        }
    }
    

    2. At the other hand, if there is no @Autowire at all (as in your example), than f object will be injected once via constructor, and setter can be used in it's common way without any injections.

提交回复
热议问题