一文搞懂spring的常用注解

spring传统做法是使用xml文件对bean进行注入和配置。通过使用spring提供的注解,可以极大的降低配置xml文件的繁琐。本文将介绍常用的注解。

@Autowired

Autowired意为:自动装配。它是按照类型进行匹配,在容器中查找匹配的bean,将其注入到autowired标注的变量中。目的是为了消除java代码块中的set和get方法。但是当遇到匹配不到所需要bean时,会报错,若我们不想让spring报错,而是显示null,需要设置autowired的属性为false。即:@Autowired(required=false)

如:定义一个类Animal,它有属性monkey,正常的使用,需要在Animal中定义该属性,再通过set和get方法,为属性赋值。但是使用autowired以后,就可以省掉了。

private Dog dog;
public void setDog(Dog dog) {
 this.dog = dog;
}
public Dog getDog() {
 return dog;
}
//替换为下边方式使用
@Autowired
private Dog dog;

二、Qualifier

Qualifier用于指定注入bean的名称。

这个注解一般和autowired搭配使用,它的使用场景为:如果匹配的bean为一个以上,spring是不知道你要具体哪个bean的,这时可以通过Qualifier指明要注入的bean。如:

@Autowired
@Qualifier("smalldog")
private Dog dog;

三、 Resource

resource注解与autowired非常类似,都是bean的注入。区别是resource可以指定name或则type进行匹配。列了一下几点区别:

  1. resource后不跟内容时,默认是按照name进行匹配,而resource默认是按照name匹配。若指定了name或则type则按照指定类型匹配。若按照指定类型,无法匹配到bean,则报错。
  2. autowired属于spring的注解,resource属于j2ee注解。即resource属于java,autowired属于spring,使用时需要引入spring的包。
@Resource(name = "smalldog")
private Dog dog;
@Resource(type = Dog.class)
private Dog dog;

四、 Service

service标签用于对应业务层的bean,若不指定name,则默认为类名首字母小写。若指定name,则意味着,告诉spring,创建该bean的实例时,bean的名字必须为指定的这个name。如:

@Service("dogService")
public class DogServiceImpl implements DogService{

 注入是,使用resource,如:
@Resource(name="dogService")
private DogService dogService;

五、 Repository

repository用于数据访问层的bean。样例如下:

@Repository(value = "dogDao")
public class DogDaoImpl implements AnimalDaoImpl{
 
@Resource
private AnimalDaoImpl dogDao;

总结:@Service 用于标注业务层,@Repository 用于标注数据访问层,@Controller 用于标注控制层,当不好分层时,可使用@Component@Scope("singleton")表示单例,prototype表示原型,每次都会new一个新的出来,作用在类上。

 
原文地址:https://www.cnblogs.com/shilei-ysl/p/11026660.html