重拾Spring(三)基于注解装配Bean

  • 注解:就是一个类,使用@注解名称。
  • 开发中:使用注解 取代 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”) 多例

  6. 注解使用前提,添加命名空间,让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.itheima.g_annotation.a_ioc"></context:component-scan>
</beans>

例子:
这里写图片描述

用@Controller替代<bean>标签:
这里写图片描述
用@AutoWired替代<property>标签,注入接口实现类:
这里写图片描述
按照名称声明dao接口:
这里写图片描述
连起来就是:
这里写图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring中,我们可以使用注解来配置和装配Bean,这可以使我们的代码更加简洁和易于维护。下面是关于如何基于注解配置和装配Bean的一些简要介绍: 1. 基于注解配置Bean 在Spring中,我们可以使用以下注解来配置Bean: - @Component:表示该类是一个Spring Bean,需要被Spring容器管理。 - @Service:表示该类是一个服务层的Bean。 - @Controller:表示该类是一个控制层的Bean。 - @Repository:表示该类是一个数据访问层的Bean。 这些注解都是基于@Component注解的衍生注解,它们的作用是更加明确地表示Bean的角色。我们可以在Bean类上添加这些注解,告诉Spring容器该类需要被管理。例如: ``` @Service public class UserService { // ... } ``` 2. 基于注解装配Bean 在Spring中,我们可以使用以下注解装配Bean: - @Autowired:自动装配Bean。 - @Qualifier:指定具体的Bean名称进行装配。 - @Resource:指定具体的Bean名称进行装配,与@Qualifier类似。 - @Value:注入一个具体的值。 使用@Autowired注解进行自动装配时,Spring会自动在容器中寻找与该类型匹配的Bean,并将其注入到类的属性中。例如: ``` @Service public class UserService { @Autowired private UserDao userDao; // ... } ``` 使用@Qualifier或@Resource注解可以指定具体的Bean名称进行装配。例如: ``` @Service public class UserService { @Autowired @Qualifier("userDaoImpl") private UserDao userDao; // ... } ``` 使用@Value注解可以注入一个具体的值。例如: ``` @Service public class UserService { @Value("10") private int maxCount; // ... } ``` 以上就是关于Spring中基于注解配置和装配Bean的简要介绍,希望能对您有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值