基于注解配置Bean

一、环境准备

Spring配置文件 applicationContext.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/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- 开启自动扫描 -->
    <context:component-scan base-package="待扫描的包"/>

</beans>

二、相关注解

  1. @Repository:标记数据访问层(dao)
  2. @Controller:标记控制器层(controller)
  3. @Service:标记业务层(service)
  4. @Component:标记通用组件
要点
  • 如果使用默认注解,则类对应的bean的id为开头字母小写的类名
  • 如果想要自定义bean的id,则对注解的value属性赋值即可
//无参 bean id为student
@Controller()
public class Student {
    private String name;
    private String id;
}

//bean id为 s1
//@Controller("s1")
@Controller(value = "s1")
public class Student {
    private String name;
    private String id;
}
  • 在类上使用以上四个注解后,Spring会自动创建相应的BeanDefinition对象,并注册到ApplicationContext中
  • 可以创建自定义注解,然后在注解上标注@Component,该自定义注解就具有了@Component的功能
  • 以上4个注解功能相同,只是作用位置不同,增强可读性
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值