在我的情况下,进行依赖注入的最佳代码结构是什么?

时间:2019-03-13 03:40:02

标签: java spring dependency-injection

这些代码是mq使用者的一部分,用于接收邮件发送任务消息,因此条目的有效负载映射包含有关电子邮件的信息,例如到达地址,用户信息。它是json格式,例如:

{
    "to": "aaa@bbb.com",
    "userId": "12",
    ...
}

我有一个监听器,用于监听mq,例如:

@Component
public class RecDownloadListener {

    private final JavaMailSender javaMailSender;

    @Autowired
    RecDownloadListener(JavaMailSender javaMailSender){
        this.javaMailSender = javaMailSender;
    }

    @Autowired
    @RabbitListener(queues = TASK)
    private void listener(RecDownloadContentBuilder builder,
                          Channel channel,
                          @Payload Map<String, String> searchParams,
                          @Header(AmqpHeaders.DELIVERY_TAG) Long deliveryTag) {

        //I want the builder could be auto injected like @Payload or @Hearder
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        String content = builder.getContent();
        String title = builder.getEmailTitle();
        String address = builder.getArriveAddress();

        //use above info to update mimeMessage and send it.
        javaMailSender.send(mimeMessage);
    }
}

最后三个参数将自动填充,它们都是从rabbitmq接收的,我想像我写的那样自动连接第一个builder,和builder一样:

@Component
@Scope(SCOPE_PROTOTYPE)
class TaskContentBuilder {

    private final Map<String, String> searchParams;
    private final UserDao userDao;
    private TemplateEngine templateEngine; //thymeleaf

    @Autowired
    RecDownloadContentBuilder(Map<String, String> searchParams, CpAccountDao cpAccountDao, TemplateEngine templateEngine) {
        this.searchParams = searchParams;
        this.cpAccountDao = cpAccountDao;
        this.templateEngine = templateEngine;
    }

    public String getEmailContent(){
        User user = userDao.findById(searchParams.get("userId"));
        Context context = new Context;
        // context.update(user.someInfomation())
        return templateEngine.process(template, context);
    }

    public String getEmailTitle(){...}
    public String getArriveAddress(){...}

}
builder的字段dao中的

很容易插入,侦听器将非常快地一个接一个地接收消息,构建器仅用于输入一条消息。我应该使(Map)searchParams作为bean函数返回吗?还是在创建构建器实例并在dao中进行设置时仅注入searchParams

0 个答案:

没有答案