Spring 的 @Autowired注解

本文解析了Spring框架中@Autowired注解的工作原理及其使用条件。包括配置识别注解、支持的注解类型、接口实现的要求及如何让Spring认识接口实现等。

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

首先查看 @Autowired为何

 

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD})
public @interface Autowired {

	/**
	 * Declares whether the annotated dependency is required.
	 * <p>Defaults to <code>true</code>.
	 */
	boolean required() default true;

}

 通过源码我们知道他是spring的一个注解接口,有一个方法

 

boolean required() default true;

 

 使用的时候必须满足如下条件:

1.spring的配置文件必须加入能够识别注解的东东

org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor

或者使用xml标注如下(注意版本)

xmlns:context

<context:component-scan base-package="org.javaeye.*"/>

支持4种注解分别为@Component, @Serivce, @Controller, @Repository

@Controller:控制层

@Serivce:业务逻辑层

@Repository:持久层

2.有注解存在

 

 

 @Autowired
    UserService userService;

 3.有对应的setter方法

 

 public void setUserService(UserService userService) {
        this.userService = userService;
    }

 4.如果是接口或者抽象类的话那么需要实现类唯一,否则创建实例出错

 

org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No unique bean of type 
[com.sohu.suc.splatform.service.UserService] is defined: 
expected single matching bean but found 2:
 [userServiceHibernateImpl, userServiceImp]
 

 5.接口的实现必须让spring认识,以bean的方式配置或者加注解让spring认识

 

@Service
public class UserServiceImpl implements UserService {
。。。。。。。
}

 综上可得spring只管理他认识的bean,有2中方式让spring知道bean的存在

1.注解方式

2.bean配置

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值