2

我想知道是否可以使用 EJB3 完成以下任务。

我有以下界面:

interface DateParser {
    Date parseDate(String input);
    String getType();
}

然后,我有几个所述接口的实现,它们根据 getType 方法中给出的信息处理不同的格式。当我的 bean 启动时,它会创建一组 DateParser 的实现,当它需要解析一个日期时,它会遍历该集合以查看哪个匹配。如果一个匹配,它使用那个来解析日期。如果没有匹配,则应用默认策略。我想避免实例化这些委托,因为每次我添加一个新策略时,它都需要在 bean 中更改代码,从而使它变得一团糟。

我更希望容器注入它在部署时找到的所有实现。有没有合理的方法来做到这一点?

谢谢

4

3 回答 3

1

Implementation of this interface should be regular classes, not beans. EJB are meant to be business services. Parsing date is IMHO a responsabiltiy that is too fine-grained for a bean.

I would much prefer to have the container inject all of the implementations it finds at deployment.

I don't think there is standard way to do that. I see only two options to dynamically fill the set with the instances:

  1. Use an external configuration files with list of class names. Reach each class name and instantiate one instance reflectively (Class.forName, Class.newInstance). Then add it to the set.

  2. Iterate over all classes in the class path, identifiy those that are implementation of DateParser. Then instantiate it reflectively, and add it to the set. Note that iterating over loadable classes is kind of tricky, see this answer.

it requires a code change in the bean making it a huge mess.

That should require a code change in a class, but not the bean itself. The bean should delegate the creation of the set, the identification of the parser, etc. to another class, IMHO.

于 2012-08-16T11:22:31.427 回答
0

是的,您可以,请参阅此示例;

    @EJB(beanName = "yourSessionEJB")
    DateParser dateParser;

您可以将其他会话 bean 名称更改为beanName属性。但是建议使用一个本地接口使用一个会话 bean,不要混淆。

于 2012-08-16T05:28:20.930 回答
0

如果要获取某个接口的所有实现,可以使用 @Any 注释和 Instance 接口。

看看这个:https ://goo.gl/Kbn0bP

于 2016-03-15T23:11:07.510 回答