class需要一个bean,但是找到了2个:

时间:2017-09-21 12:09:30

标签: java spring spring-mvc

我有以下界面:

public interface MailSender {
    void sender(String to, String subject,String body);
}

有2个实现:

public class SmtpkMailSender implements MailSender   {

    static Log log=LogFactory.getLog(MailSender.class); 

    public void sender(String to, String subject,String body){
        log.info("SMTP To: "+to);
        log.info("SMTP Subjecy: "+subject);
        log.info("SMTP body: "+body);
    }

}

,第二个是:

@Primary
public class MockMailSender implements MailSender   {

    static Log log=LogFactory.getLog(MailSender.class); 

    public void sender(String to, String subject,String body){
        log.info("To: "+to);
        log.info("Subject: "+subject);
        log.info("body: "+body);
    }

}

我在控制器类中使用了依赖注入,如下所示:

@RestController
public class MailController {

    @Autowired
    private MailSender smtpkMailSender;

    @RequestMapping("/send")
    public String send(){
        smtpkMailSender.sender("Person", "Important", "Take Care");
        return "mail is sent";
    }
}

最后我有一个包含我的Beans的配置类:

@Configuration
public class MailConfig {

    @Bean
    public SmtpkMailSender getSmtpkMailSender(){
        return new SmtpkMailSender();
    }

    @Bean
    public MockMailSender getMockMailSender(){
        return new MockMailSender();
    }

}

不幸的是,当我运行我的应用程序时,它抱怨:

Description:

Field smtpkMailSender in com.example.demo.MailController required a single bean, but 2 were found:
    - getSmtpkMailSender: defined by method 'getSmtpkMailSender' in class path resource [com/example/mail/MailConfig.class]
    - getMockMailSender: defined by method 'getMockMailSender' in class path resource [com/example/mail/MailConfig.class]


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

如您所见,虽然我已将MockMailSender指定为主要版本,但春天仍会抱怨,并且无法识别它

3 个答案:

答案 0 :(得分:4)

您可以使用@Qualifier注释来指定您希望自动装配的实施的特定类型。

@RestController
public class MailController {

   @Autowired
   @Qualifier("smtpkMailSender")
   private MailSender smtpkMailSender;

   @RequestMapping("/send")
   public String send(){
      smtpkMailSender.sender("Person", "Important", "Take Care");
      return "mail is sent";
  }

}

答案 1 :(得分:3)

由于你使用的是java配置,你应该用@Primary注释标记配置方法,而不是类:

@Configuration
public class MailConfig {
    @Bean
    public SmtpkMailSender getSmtpkMailSender(){
        return new SmtpkMailSender();
    }

    @Bean
    @Primary
    public MockMailSender getMockMailSender(){
        return new MockMailSender();
    }
}

答案 2 :(得分:1)

您可以使用

@Bean(name="mockMailSender")
public MockMailSender getMockMailSender() { }

,然后用

装饰自动连线字段
@Autowired
@Qualifier("mockMailSender")
private MailSender smtpkMailSender;