Spring注解

本文详细介绍了Spring框架中关键注解的使用方法,包括@Component、@ComponentScan、@Configuration及@Qualifier的具体应用场景,帮助读者理解如何利用这些注解来实现依赖注入。

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

@Component :把普通pojo实例化到spring容器中,相当于配置文件中的 。

<bean id="" class=""/>


@ComponentScan(basePackages = {"",""}):启用组件扫描,如果没有其它配置的话(@ComponentScan),默认会扫描与配置类相同的 包,比如,扫描的时候查找带有@Component注解的类,并在Spring中自动为其创建一个bean。对应的xml为:

<context:component-scan base-package="chapter4"></context:component-scan>


@Configuration:与xml配置文件等效,看下面例子。

@Configuration
@ComponentScan
public class chapter4Config {
    @Bean
    public Audience audience()
    {
        return new Audience();
    }
}

相当于以下的xml

<?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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


        <context:component-scan base-package="chapter4"></context:component-scan>
        <bean id="audience" class="chapter4.Audience"></bean>

</beans>


@Qualifier具体用法:

@Autowired注释进行自动注入时,Spring 容器中匹配的候选 Bean 数目必须有且仅有一个。当找不到一个匹配的 Bean 时,Spring 容器将抛出 BeanCreationException 异常,并指出必须至少拥有一个匹配的 Bean。@Autowired 默认是按照byType进行注入的,如果发现找到多个bean,则,又按照byName方式比对,如果还有多个,则报出异常。@Autowired可以手动指定按照byName方式注入,使用@Qualifier标签。用法如下代码:


@Autowired
    @Qualifier("article")
    Performance performance1;

    @Autowired
    @Qualifier("musician")
    Performance performance2;
//Article与Musician类都实现了Performance,Article与Musician都注入到了Spring容器中
  
  




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值