常用的注解
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/>