spring @Autowire property vs setter [英] spring @Autowire property vs setter

查看:161
本文介绍了spring @Autowire property vs setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

anotate @Autowired到某个属性或在setter中有什么区别?

What is the difference between anotate @Autowired to a property or do it in the setter?

据我所知他们都有相同的结果,但是有没有理由使用其中一个?

As far as I know they both have the same result, but is there any reason to use one over the other?

更新(更简洁)

这个

package com.tutorialspoint;

import org.springframework.beans.factory.annotation.Autowired;

public class TextEditor {
   private SpellChecker spellChecker;

   @Autowired
   public void setSpellChecker( SpellChecker spellChecker ){
      this.spellChecker = spellChecker;
   }

   public void spellCheck() {
      spellChecker.checkSpelling();
   }
}

这个

package com.tutorialspoint;

import org.springframework.beans.factory.annotation.Autowired;

public class TextEditor {
   @Autowired
   private SpellChecker spellChecker;

   public TextEditor() {
      System.out.println("Inside TextEditor constructor." );
   }

   public void spellCheck(){
      spellChecker.checkSpelling();
   }
}


推荐答案

随着 @Autowired 注释,您不需要setter方法。一旦你的bean的构造函数完成了分配/创建对象,Spring将扫描这个注释并注入你注释的对象实例。

With @Autowired annotation, you don't need a setter method. Once your bean's constructor is done with allocating/creating the object, Spring will scan for this annotation and would inject the object instances that you annotated.

如果你有setter和如果你还在使用xml配置,你会明确设置属性。

While if you have setter and if you are still using xml config, you would explicitly set properties.

话虽如此,你可以使用autowired annotation来注释你的构造函数和setter方法,我更喜欢这样做以后我会灵活地离开Spring(虽然我不会这样做)。

Having said that, You could annotate your constructor and setter method with autowired annotation which i would prefer as this would give me flexibility later on to move away from Spring (although i wont do it).

这篇关于spring @Autowire property vs setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆