Spring纯注解开发+bean


你知道吗?昨天下午我被人骂了,她们说我往楼下滴水,把阳台上晾的衣服都打湿了,只有我知道那不是水,是我趴在阳台上想你流的眼泪


前言

项目结构:
在这里插入图片描述


一、Spring纯注解开发

1.定义bean

在这里插入图片描述
在上图中,需要定义bean,其名称,配置类。采用注解开发模式,就需要代替上面三个步骤。

  1. 在要定义的类上加上注解@Component()
  2. 定义名称@Component(“bookDao”)
  3. 配置文件需要知道这个,就需要在配置文件中加入以下内容来进行扫描:

在这里插入图片描述
:@componet()在所以类中均可使用,在web开发中也可使用以下,和它没有区别

  • @Controller() 表现层
  • @Service() 业务层
  • @Repository() 数据层

3.纯注解开发模式

上面我们依然使用了配置文件,在这次中,我们就将配置文件全部删除,真正做到纯注解。

(1)创建配置类:

既然没有了配置文件,那么就需要有和配置文件一样效果的东西,这就是配置类
代码:

package com.hewen.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**声明当前类为Spring配置类*/
@Configuration    //相当于配置文件中的外面那一圈
//设置bean扫描路径,多个路径书写为字符串数组格式
@ComponentScan("com.hewen.service")   // 多个用数组形式
public class SpringConfig {
}
  • @Configuration的作用就是定义这个类为配置类
  • @ComponentScan() 设置bean扫描路径


在这里插入图片描述

我们看@ComponentScan()注解的源码就会发现它使用的是字符串数组,所以当设置多个时就要使用数组形式
{“com.hewen.service”,“com.hewen.dao”}

(2)App类:

使用了注解开发后,就不需要加载配置文件

import com.hewen.config.SpringConfig;
import com.hewen.dao.BookDao;
import com.hewen.service.BookService;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AppForAnnotation {
    public static void main(String[] args) {
        //AnnotationConfigApplicationContext加载Spring配置类初始化Spring容器
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        BookDao bookDao = (BookDao) ctx.getBean("bookDao");
        System.out.println(bookDao);
        //按类型获取bean
        BookService bookService = ctx.getBean(BookService.class);
        System.out.println(bookService);
    }
}

二、总结:

在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

开心比较堵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值