多个实现类,spring 实现自动注入

一、接口

public interface IService {

    void beanTest();
}
二、实现类
@Service("dog")
public class DogServiceImpl implements IService{
    @Override
    public void beanTest() {
        System.out.println(" i am dog");
    }
}
@Service("cat")
public class CatServiceImpl implements IService{
    @Override
    public void beanTest() {
        System.out.println(" i am cat cat");
    }
}

三、测试

package com.web.webtest;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.util.List;

@SpringBootTest(classes = WebtestApplication.class)
class WebtestApplicationTests {

    @Resource
    List service;

    //会注入 同名的dog 
    @Resource
    IService dog;
    //会注入 同名的 cat
    @Resource
    IService cat;

    @Test
    void contextLoads() {
    }

    /**
     *  i am cat cat
     *  i am dog
     */
    @Test
    void serviceTest(){
     for (IService ss:service){
         ss.beanTest();
     }
    }

    /**
     * i am dog
     */
    @Test
    void dog(){
        dog.beanTest();
    }

    /**
     *  i am cat cat
     */
    @Test
    void  cat(){
        cat.beanTest();
    }
}

你可能感兴趣的:(多个实现类,spring 实现自动注入)