Spring @Bean - Spring Bean 的创建取决于服务类名

问题描述

我使用 Spring 4.2.8 并且我有下面的服务类。如果此类具有名称 ScheduleEmailCreateAndSendServiceImpl 则一切正常(在开始时调用方法 generalEmailMessage 以创建 Spring Bean) 如果我将这个类重命名EmailCreateAndSendServiceImpl,那么在开始时将不会调用方法 generalEmailMessage - 有谁知道为什么?

@Service("emailCreateAndSendService")
public class ScheduleEmailCreateAndSendServiceImpl extends AbstractService 
implements EmailService {

protected EmailMessage generalMessage;

@Override
public void createAndSendMessage(String receiver,boolean emailActive,Object[] values) throws BusinessException {
    // create and send email
}

@Bean
public EmailMessage generalEmailMessage() {
    this.generalMessage = new GeneralEmailinformationMessage();
    return generalMessage;
}

}

[编辑]

这个代码是一样的

@Configuration
public @Data class ScheduleGeneralEmailConfiguration {

protected EmailMessage generalMessage;

public ScheduleGeneralEmailConfiguration() {
    System.out.println("asdf");
}

@Bean
public EmailMessage generalEmailMessage() {
    this.generalMessage = new GeneralEmailinformationMessage();
    return generalMessage;
}

}

解决方法

@Bean 带注释的方法应该在 @Configuration 带注释的类中。

您也可以将@Bean注解的方法放在Spring Boot应用的主类中,注解@SpringBootApplication,封装@Configuration@EnableAutoConfiguration和{{1} } 注释。

确保您的 @ComponentScan 注释类放置在 Spring Boot Application 类的同一个包或子包中