@Resource、@Autowired、@Qualifier的注解注入及区别

一、前言

  spring4.0+版本开发中使用到了自动装配技术,故有了这篇总结博文,后面对接口、实现类、装配注入,做详细解释。

二、@Resource、@Autowired、@Qualifier 定义说明:

  1、@Resource 默认根据名字注入,其次按照类型搜索

  2、@Autowired 根据类型注入

  3、@Autowired @Qualifie("userService") 两个结合起来可以根据名字和类型注入

三、程序示例

1、定义接口 GameService

package com.tlong.service;

/**
 * 游戏接口
 */
public interface GameService {
    public void play();
}

2、定义两个实现类 GloryOfKingsImpl 、PubgImpl 

package com.tlong.service;

import org.springframework.stereotype.Service;

/**
 * 王者荣耀
 */
@Component
public class GloryOfKingsImpl implements GameService {

    @Override
    public void play() {
        System.out.println("王者荣耀 游戏开始......");
    }
}
package com.tlong.service;

import org.springframework.stereotype.Service;

/**
 * 绝地求生
 */
@Component
public class PubgImpl implements GameService {
    @Override
    public void play() {
        System.out.println("绝地求生 游戏开始......");
    }
}

3、定义测试类 TestController

public class TestController {

    //简洁写法:保证变量名是实现类的名称,注意:首字符小写
    @Autowired
    private GameService gloryOfKingsImpl;

    //简洁写法:保证变量名是实现类的名称,注意:首字符小写,此处@Resource和@Autowired实现方式相同
    @Resource
    private GameService pubgImpl;



    //如果想指定不一样的变量名要怎么写呢?不能使用上面的自动装配技术也可以理解,在实现类中使用了@Component注解,spring会自为其创建一个bean并给定ID为gloryOfKingsImpl,spring并不知道该变量需要装配哪个实现类
    //写法如下
    //1、使用@Autowired和@Qualifier实现,注意:@Qualifier中的首字符小写
    @Autowired
    @Qualifier("gloryOfKingsImpl")
    private GameService wzry;

    //2、使用@Resource实现,注意:@Resource中的首字符小写
    @Resource(name = "pubgImpl")
    private GameService jdqs;

    public void playGame(){
        gloryOfKingsImpl.play();
        pubgImpl.play();
        wzry.play();
        jdqs.play();
    }
}

猜你喜欢

转载自www.cnblogs.com/guoyinli/p/9051258.html