@Autowired 注解的作用是什么?

@Autowired由Spring框架定义,当Spring框架的项目在运行时如果发现由它管理的Bean对象中有使用@Autowired注解描述的属性/方法,Spring会按照指定规则为属性/方法赋值(DI)。

@Autowired 注解如何使用?

@Autowired是一种注解,可以对构造器、方法、参数、字段和注解进行标注,源码如下:

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
	// @Autowired 只有一个required元素,默认是true
	// require=ture 时,表示解析被标记的属性/方法,在容器中一定有对应的bean存在,否则报错。
	// require=false时,表示解析被标记的属性/方法,在容器中没有找到对应的bean依然不会报错。
    boolean required() default true;
}

(1). @Autowired一般用在Controller层中用来装配Service对象,当同一个Service接口对象有多个实现时,需要使用@Qualifier来制定具体的装载依赖,否则会报错,除非用@Autowired标注的属性/方法的类型是Map或者List:No qualifying bean of type ‘com.hadoopx.file.service.ISysFileService’ available: expected single matching bean but found 2: LocalSysFileServiceImpl,FastDfsSysFileServiceImpl,当然这个问题也可以使用@Primary来解决。
NoUniqueBeanDefinitionException,说明有多个满足条件的bean进行自动装配,程序无法正确做出判断使用哪一个,通过将@Qualifier注解与我们想要使用的特定Spring bean的名称一起进行装配,Spring框架就能从多个相同类型并满足装配要求的bean中找到我们想要的
(2). @Autowired根据类型进行自动装配,如果需要按名称进行装配,则需要配合@Qualifier使用。
(3). @Autowired在装配依赖对象时,默认要求依赖对象必须存在,如果允许为NULL,需要设置required属性为false。
(4). 被@Autowired标注的属性/方法所在的类,需要是Spring容器中的bean。

	@Service
	public class SysOperLogServiceImpl implements ISysOperLogService {
	    @Autowired
	    private SysOperLogMapper operLogMapper;
	}
	
	@RestController
	@RequestMapping("/user")
	@Api(value = "管理员管理", description = "提供对管理员对象的增删改查")
	public class SysUserController extends BaseController {
	    @Autowired
	    private ISysUserService userService;
	    @Autowired
	    private ISysRoleService roleService;
	}

(5). 被@Autowired标注的属性/方法的类型是Map且Key为String类型,Spring则会把所有符合该类型的bean装载到Map中,key是bean名称,value则为该bean的实例。在简单工程模式中,可以使用该特性替换传统的将服务实现存入Map的方式。
(6). 被@Autowired标注的属性/方法的类型是List,Spring则会把所有符合该类型的bean装载到List集合中。
(7). @Autowired与@Resource都可以用来装配bean,都可以写在字段上。@Autowired默认按类型装配,@Resource(这个注解属于J2EE的),默认安照名称进行装配,名称可以通过name属性进行指定。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐