基于注解的装配Bean

本文介绍了如何使用注解来替代XML配置文件进行Bean的装配。@Component及其衍生注解@Repository、@Service和@Controller用于标记不同层的类。依赖注入可通过@Autowired和@Resource实现,同时支持按照类型和名称注入。@PostConstruct和@PreDestroy分别用于标记初始化和销毁方法。@Scope("prototype")用于创建多例Bean。注解的使用需要添加相应命名空间并开启扫描。注解与XML配置文件可以混合使用,但通常不同时使用<context:component-scan>和<context:annotation-config>,前者扫描注解类并自动装配,后者仅在XML与注解混合使用时启用注入。

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

注解:就是一个类,使用@注解名称

开发中:使用注解 取代 xml配置文件

1. @Component取代<bean class="">

   @Component("id")取代 <bean   id="" class="">

2.web开发,提供3个@Component注解衍生注解(功能一样)取代<bean   class="">

       @Repository:dao层

       @Service:service层

       @Controller:web层

3.依赖注入,给私有字段设置,也可以给setter方法设置

       普通值:@Value("")

       引用值:

              方式1:按照【类型】注入

                     @Autowired

              方式2:按照【名称】注入1

                     @Autowired

                     @Qualifier("名称")

              方式3:按照【名称】注入2

                     @Resource("名称")

4.生命周期

       初始化:@PostConstruct

       销毁:@PreDestroy

5.作用域

       @Scope("prototype")多例

但是需要注意的是,注解使用前提是需要添加命名空间,让spring扫描含有注解类。

<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="com.zju.annotation_0"></context:component-scan>
</beans>

注解和XML配置文件混合使用:

1.将所有的bean都配置xml中

      <bean  id=""  class="">

2.将所有的依赖都使用注解

       @Autowired

       默认是不生效的,为了生效,需要在xml配置:<context:annotation-config>

总结:

注解1:<context:component-scan    base-package=" ">

注解2:<context:annotation-config>

1.一般情况两个注解不一起使用。

2. “注解1”扫描含有注解(@Component等)类,注入注解自动生效。

   “注解2”只在xml和注解(注入)混合使用时,使注入注解生效。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值