微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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 类的同一个包或子包中

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。