spring、springboot 注入接口(实现)

在平时的开发中可能会有定义了一些接口,有多个实现类,且每个实现类都可能被注入,在这个时候就可以将接口(的实例)注入进去

1、如果接口有一个实现类,

        则可以直接通过注入接口的形式来注入实例

    定义一个接口

package com.example.demo.interface2.practice;

/**
 * @ProjectName: demo
 * @Package: com.example.demo.interface2.practice
 * @ClassName: PracticeAutoInterface
 * @Author: yu
 * @Description: 测试注入接口
 * @Date: 2020/5/28 10:59
 * @Version: 1.0
 */
public interface PracticeAutoInterface {
    public void print();
}

    实现接口

package com.example.demo.service.practiceAuto;

import com.example.demo.interface2.practice.PracticeAutoInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @ProjectName: demo
 * @Package: com.example.demo.service
 * @ClassName: Service2AutoInterface
 * @Author: yu
 * @Description: 测试注入接口
 * @Date: 2020/5/28 11:04
 * @Version: 1.0
 */
@Slf4j
@Service
public class Service2AutoInterface implements PracticeAutoInterface {
    @Override
    public void print() {
        int aa = 1;
        log.info("成功访问实现{}",aa);
    }
}

    然后写一个controller来注入实现并查看接口

package com.example.demo.controller;

import com.example.demo.entity.E;
import com.example.demo.interface2.practice.PracticeAutoInterface;
import com.example.demo.practice.PracticeJava8Service;
import com.example.demo.result.methodResult.Msg;
import com.example.demo.service.TestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ProjectName: demo
 * @Package: com.example.demo.controller
 * @ClassName: Java8Controller
 * @Author: yu
 * @Description: 其他技能测试类
 * @Date: 2020/5/9 13:32
 * @Version: 1.0
 */
@RestController(value = "/other")
@AllArgsConstructor(onConstructor_ = {@Autowired})
@Api(tags = "其他技能测试类")
public class OtherController {


    @RequestMapping(value = "/autoInterface",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE )
    @ApiOperation(value = "测试注入接口",notes = "。。。")
    public void autoInterfaceMethod(){
        practiceAutoInterface.print();
    }



   
    private PracticeAutoInterface practiceAutoInterface;


}

    结果

2020-05-28 11:39:19.706  INFO 14408 --- [nio-8082-exec-8] c.e.d.s.p.Service2AutoInterface          : 成功访问实现1

2、如果接口有多个实现类

    再次创建一个实现类

package com.example.demo.service.practiceAuto;

import com.example.demo.interface2.practice.PracticeAutoInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

/**
 * @ProjectName: demo
 * @Package: com.example.demo.service
 * @ClassName: Service2AutoInterface
 * @Author: yu
 * @Description: 测试注入接口
 * @Date: 2020/5/28 11:04
 * @Version: 1.0
 */
@Slf4j
@Service
入而不会报错
public class Service2AutoInterface2 implements PracticeAutoInterface {
    @Override
    public void print() {
        int aa = 2;
        log.info("成功访问实现{}",aa);
    }
}

这个时候在启动项目的时候,会提示找到两个相同的bean(名称),Spring给了明确提示说有2个Bean被找到,但是只需要一个。建议使用@Primary注解使其优先被选择,或者使用@Qualifier指定注入一个Bean。

方式1

此时可以通过@Primary注解,来指定优先注入哪个bean

package com.example.demo.service.practiceAuto;

import com.example.demo.interface2.practice.PracticeAutoInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

/**
 * @ProjectName: demo
 * @Package: com.example.demo.service
 * @ClassName: Service2AutoInterface
 * @Author: yu
 * @Description: 测试注入接口
 * @Date: 2020/5/28 11:04
 * @Version: 1.0
 */
@Slf4j
@Service
@Primary// 如果有多个接口接口实例要被注入且没有配置独有的bean名称,次注解可以是spring优先被注入而不会报错
public class Service2AutoInterface2 implements PracticeAutoInterface {
    @Override
    public void print() {
        int aa = 2;
        log.info("成功访问实现{}",aa);
    }
}

再次访问结果为:

2020-05-28 11:47:01.108  INFO 15152 --- [nio-8082-exec-1] c.e.d.s.p.Service2AutoInterface2         : 成功访问实现2

方式2

使用@Qualifier注解,去掉Service2AutoInterface2 的@Primary注解,改写controller的代码:

package com.example.demo.controller;

import com.example.demo.entity.E;
import com.example.demo.interface2.practice.PracticeAutoInterface;
import com.example.demo.practice.PracticeJava8Service;
import com.example.demo.result.methodResult.Msg;
import com.example.demo.service.TestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ProjectName: demo
 * @Package: com.example.demo.controller
 * @ClassName: Java8Controller
 * @Author: yu
 * @Description: 其他技能测试类
 * @Date: 2020/5/9 13:32
 * @Version: 1.0
 */
@RestController(value = "/other")
@Api(tags = "其他技能测试类")
public class OtherController {


    @RequestMapping(value = "/autoInterface",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE )
    @ApiOperation(value = "测试注入接口",notes = "。。。")
    public void autoInterfaceMethod(){
        practiceAutoInterface.print();
    }


   @Autowired
   @Qualifier("service2AutoInterface")
    private PracticeAutoInterface practiceAutoInterface;


}

再次执行并查看结果:

2020-05-28 11:55:28.967  INFO 13436 --- [nio-8082-exec-1] c.e.d.s.p.Service2AutoInterface          : 成功访问实现1

注意:使用@Qualifier注入指定Bean的时候,若没有指明Bean的名称,则其默认名称是首字母小写的类名。如实例中的                @Qualifier("service2AutoInterface")

当然也可以这样

Service2AutoInterface :

@Slf4j
//@Service
@Service( "Service2AutoInterface")
public class Service2AutoInterface implements PracticeAutoInterface {
    @Override
    public void print() {
        int aa = 1;
        log.info("成功访问实现{}",aa);
    }
}


Service2AutoInterface2 :



@Slf4j
//@Service
@Service("Service2AutoInterface2")
//@Primary// 如果有多个接口接口实例要被注入且没有配置独有的bean名称,次注解可以是spring优先被注入而不会报错
public class Service2AutoInterface2 implements PracticeAutoInterface {
    @Override
    public void print() {
        int aa = 2;
        log.info("成功访问实现{}",aa);
    }
}


controller:

  @Autowired
    @Qualifier("Service2AutoInterface")
    private PracticeAutoInterface practiceAutoInterface;

方式3、

使用@Resource(name = "Service2AutoInterface"),--(没有括号内内容的话,默认byName。与@Autowired干类似的事。)

package com.example.demo.controller;

import com.example.demo.entity.E;
import com.example.demo.interface2.practice.PracticeAutoInterface;
import com.example.demo.practice.PracticeJava8Service;
import com.example.demo.result.methodResult.Msg;
import com.example.demo.service.TestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ProjectName: demo
 * @Package: com.example.demo.controller
 * @ClassName: Java8Controller
 * @Author: yu
 * @Description: 其他技能测试类
 * @Date: 2020/5/9 13:32
 * @Version: 1.0
 */
@RestController(value = "/other")
@Api(tags = "其他技能测试类")
public class OtherController {


    @RequestMapping(value = "/autoInterface",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE )
    @ApiOperation(value = "测试注入接口",notes = "。。。")
    public void autoInterfaceMethod(){
        practiceAutoInterface.print();
    }


     @Resource(name = "Service2AutoInterface")
    private PracticeAutoInterface practiceAutoInterface;


}

结果为:

2020-05-28 12:02:22.207  INFO 14916 --- [nio-8082-exec-1] c.e.d.s.p.Service2AutoInterface          : 成功访问实现1

@Autowired与@Resource区别(摘抄自:@Autowired 与@Resource的区别(详细)_jasonhouse的博客-CSDN博客_@autowired和@resource的区别

1、 @Autowired与@Resource都可以用来装配bean. 都可以写在字段上,或写在setter方法上。

2、 @Autowired默认按类型装配(这个注解是属业spring的),默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用,如下:

3、@Resource(这个注解属于J2EE的),默认按照名称进行装配,名称可以通过name属性进行指定,如果没有指定name属性,当注解写在字段上时,默认取字段名进行安装名称查找,如果注解写在setter方法上默认取属性名进行装配。当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。

推荐使用:@Resource注解在字段上,这样就不用写setter方法了,并且这个注解是属于J2EE的,减少了与spring的耦合。这样代码看起就比较优雅。

spring @Qualifier注解

@Autowired是根据类型进行自动装配的。如果当Spring上下文中存在不止一个UserDao类型的bean时,就会抛出BeanCreationException异常;如果Spring上下文中不存在UserDao类型的bean,也会抛出BeanCreationException异常。我们可以使用@Qualifier配合@Autowired来解决这些问题。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值