Spring的常用的注解

常用的注解

1.@Autowired:自动装配,先通过类型class,再通过名字id

2.@Qualifier:当@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解@Autowired完成的时候【eg:<bean id="dog22" class="com.cbbpp.pojo.Dog"/>和<bean id="dog222" class="com.cbbpp.pojo.Dog"/>】,我们可以使用@Qualifier(value="xxx")去配置@Autowired的使用,指定一个唯一的bean对象注入

3.@Resource:自动装配,先通过名字id,再通过类型class

4.@Nullable:当我们使用@Autowired(required=false)的时候,其含义等价于@Nullable,就是使改属性可以为空值null,否则不允许为空值

5-6.@Component和@Value:

package com.cbbpp.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//  等价于 <bean id="user" class="com.cbbpp.pojo.User"/>
//  @Component意思为组件
@Component
public class User {
    public String name;
    //等价于<property name="name" value="土拨鼠"/>
    @Value("土拨鼠")
    public void setName(String name){
        this.name = name;
    }
}

@Component的衍生注解,我们在web开发中,会按照mvc三层架构分层,@Component、@Repository、@Service、@Controller四个注解的作用都是一样的是等价的,都会被扫描作为一个Component,都是把某个类Bean装配到IOC容器中

  • dao【@Repository】
  • service【@Service】
  • controller【@Controller】

7.@Scope:可以设置bean的作用域,可以选择singleton和prototype

小结:

  • 一般xml用来管理bean
  • 注解只负责完成属性的注入
  • 我们在使用过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持
    <!--指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="com.cbbpp"/>
    <context:annotation-config/>

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值