使用Spring注解怎么实现Bean自动装配功能

这篇文章将为大家详细讲解有关使用Spring注解怎么实现Bean自动装配功能,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

使用须知:

1.导入约束:context约束

2.配置注解的支持: context:annotation-config/

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
  https://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context
  https://www.springframework.org/schema/context/spring-context.xsd">

 <context:annotation-config/>

</beans>

@Autowired

通过ByType的方式实现自动装配,且必须要求该对象存在。

直接在属性上使用,也可以在set方法上使用。

使用Autowired时,可以不用编写set方法,前提是你这个自动装配的属性在IOC容器中存在,且符合Byname方式

@Autowired
private Cat cat;

@Qualifier

@Autowired
@Qualifier(value = "dog111")
private Dog dog;

如果@Autowired自动装配的环境比较复杂,可以使用@Qualifier来辅助@Autowired完成自动装配,

通过@Qualifier(value = “dog111”)指定Bean的ID来装配。

关于使用Spring注解怎么实现Bean自动装配功能就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。