Spring注解

一.装配bean基于注解

1. @Component

@component(代替的是<bean class="..."/>)
@component("person")(代替的是<bean id="person" class="..."/>)

2.web开发,提供3个@Component注解衍生注解(功能一样)

@Repository :dao层
@Service:service层
@Controller:web层

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

普通值:@Value("")
引用值:
    方式1:按照【类型】注入
        @Autowired
    方式2:按照【名称】注入1
        @Autowired
        @Qualifier("名称")
    方式3:按照【名称】注入2
        @Resource("名称")

4.生命周期

初始化:@PostConstruct
销毁:@PreDestroy

5.作用域

@Scope("prototype") 多例

二.Resource注解(引用)

@Resource
    private Student student;
一定要启动依赖注入的注解解析器 
   <context:annotation-config></context:annotation-config>

原理:

1.Spriing容器启动的时候会创建在applicationContext.xml中的<bean>对象
2.Spring容器解析到context:annotation-config时,会在Spring管理的bean的范围内查找这些类的属性上是否有@Resource注解
3.Spring解析@Resource的name属性,
    如果为空,拿注解所在的属性的名称与Spring容器中的id去匹配,如果匹配成功则赋值,否则,按照类型去匹配,还没有成功,就报错。
    如果不为空,则拿name的属性值跟Spring容器中的id去匹配,不成功则报错

三.扫描注解

@Component("student")
public class Student {
...
}

@Component("person")
public class Person {
    @Resource(name="student")
    private Student student;
    ...
}
配置文件中:
<context:component-scan base-package="com.spring.scan"></context:component-scan>

原理

1.启动Spring容器,Spring容器解析配置文件
2.Spring解析到context:component-scan ,会在指定的base-package包及子包中扫描所有的类,看哪些类上有@Commonent注解
3.其实相当于将注解解析成<bean/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值