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

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

使用@Autowired

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

使用@Autowired在属性上

  这个注解可以直接使用在属性上,不再需要为属性设置getter/setter访问器。

@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;
    }
}

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

使用@Autowired 在构造方法上

  @Autowired注解也可以用在构造函数上。在下面的示例中,当在构造函数上使用注释时,在创建FooService时,会将FooFormatter的实例作为参数注入构造函数:

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

补充:在构造方法中使用@Autowired,我们可以实现在静态方法中使用由容器管理的Bean

@Component
public class Boo {

    private static Foo foo;

    @Autowired
    private Foo foo2;

    public static void test() {
        foo.doStuff();
    }
}
使用@Qualifier取消歧义

  定义Bean时,我们可以给Bean起个名字,如下为barFormatter

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

  当我们注入时,可以使用@Qualifier来指定使用某个名称的Bean,如下:

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

参考链接:

转载于:https://www.cnblogs.com/MrSaver/p/10888889.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值