Spring 注解

@Autowired是Spring从2.5版本开始引入的注解,用于实现依赖注入。它可以用于变量初始化、赋值以及构造函数,使得在类中可以直接使用所需的服务。注意,@Autowired不能应用于静态变量,因为静态变量在类加载时初始化,而Spring容器晚于类加载。当没有匹配的Bean时,Spring会抛出NoSuchBeanDefinitionException异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先写 Autowired

Autowired

简介

始于 Spring 2.5 版本,这个版本的框架是注解驱动的依赖注入,主要的注解就是@Autowired,负责解析和注入 Bean。

使用

2.5 以前所有的 Bean 注入都是在 Spring 的配置文件中,Spring 容器能自动依赖注入。可以用于变量初始化(常用)、赋值和构造函数。

注册 Bean

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

用于变量初始化

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

用于赋值

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

用于构造函数

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

注意点

@Autowired 不能是 static 的,因为静态变量会在类启动后最先加载,当类加载器加载静态变量时,Spring 的上下文环境还没有被加载。
@Autowired 本身就是单例模式,只会在程序启动时执行一次,所以不需要加 final。

可选项

当 Spring 不能解析 Bean 的时候就会跑异常

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type [com.autowire.sample.FooDAO] found for dependency: 
expected at least 1 bean which qualifies as autowire candidate for this dependency. 
Dependency annotations: 
{@org.springframework.beans.factory.annotation.Autowired(required=true)}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值