SpringMVC:学习笔记(11)——依赖注入与@Autowired

SpringMVC:学习笔记(11)——依赖注入与@Autowired 

使用@Autowired

  从Spring2.5开始,它引入了一种全新的依赖注入方式,即经过@Autowired注解。这个注解容许Spring解析并将相关bean注入到bean中。java

使用@Autowired在属性上

  这个注解能够直接使用在属性上,再也不须要为属性设置getter/setter访问器。spring

@Component("fooFormatter")
public class FooFormatter {
 
    public String format() {
        return "foo";
    }
}

  在下面的示例中,Spring在建立FooService时查找并注入fooFormatter函数

@Component
public class FooService {
     
    @Autowired
    private FooFormatter fooFormatter;
 
}

使用@Autowired在Setters上

  @Autowired注解可用于setter方法。在下面的示例中,当在setter方法上使用注释时,在建立FooService时使用FooFormatter实例调用setter方法:学习

public class FooService {
 
    private FooFormatter fooFormatter;
 
    @Autowired
    public void setFooFormatter(FooFormatter fooFormatter) {
            this.fooFormatter = fooFormatter;
    }
}

  这个例子与上一段代码效果是同样的,可是须要额外写一个访问器。this

使用@Autowired 在构造方法上

  @Autowired注解也能够用在构造函数上。在下面的示例中,当在构造函数上使用注释时,在建立FooService时,会将FooFormatter的实例做为参数注入构造函数:spa

public class FooService {
 
    private FooFormatter fooFormatter;
 
    @Autowired
    public FooService(FooFormatter fooFormatter) {
        this.fooFormatter = fooFormatter;
    }
}  

补充:在构造方法中使用@Autowired,咱们能够实如今静态方法中使用由容器管理的Beanorm

@Component
public class Boo {

    private static Foo foo;

    @Autowired
    private Foo foo2;

    public static void test() {
        foo.doStuff();
    }
}

使用@Qualifier取消歧义

  定义Bean时,咱们能够给Bean起个名字,以下为barFormatterblog

@Component("barFormatter")
public class BarFormatter implements Formatter {
 
    public String format() {
        return "bar";
    }
}

  当咱们注入时,能够使用@Qualifier来指定使用某个名称的Bean,以下:get

public class FooService {
     
    @Autowired
    @Qualifier("fooFormatter")
    private Formatter formatter;
 
}

参考连接:form

相关文章
相关标签/搜索