Spring注解(简便地使用 Bean )

目录

0. 前置工作

1. 将 Bean 存储到容器

2. 对象注入(对象装配)【从容器中将对象读取出来】


0. 前置工作

创建Maven项目后,在pom.xml中添加Spring所必须的依赖。

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
    </dependencies>

在 resource 文件夹下,创建spring-config.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:content="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 https://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 👇配置bean注解扫描的根路径(方面后面更简单存储对象到spring容器),当前com.beans表示当前项目java文件夹下所有要存放到spring中bean的根路径-->
    <content:component-scan base-package="com.beans"></content:component-scan>
</beans>

1. 将 Bean 存储到容器

  • 【法一】使用五大类注解实现
    @Controller【控制器】
    @Service【服务】
    @Repoistory【仓库】
    @Configuration【配置】
    @Component【组件】
  • 【法二】使用 @Bean 方法注解实现(前提:方法所在的类要加五大类注解)

添加注解后,更加简单地实现了将一个对象存储到Spring当中
        (默认会按类名自动扫描注入为小驼峰方式的bean name

软件项目分层

2. 对象注入(对象装配)【从容器中将对象读取出来】

  1. 属性注入Bean对象(字段注入) @Autowired / @Resource
  2. 构造方法注入(官方推荐) @Autowired,当该类只有一个构造方法时可以省略
  3. Setter注入 @Autowired / @Resource

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值