public class Publisher {
@Autowired
@Qualifier("target1")
Connection target1;
@Autowired
@Qualifier("target2")
Connection target2;
private final List<Connection> connections;
public Publisher(List<Connection> connections) {
this.connections = connections;
}
public void publish(String target) {
if (target.equalsIgnoreCase("all")) {
for (Connection connection : connections) {
doSomething(connection);
}
} else if (target.equalsIgnoreCase("Person1")) {
doSomething(target1);
} else if (target.equalsIgnoreCase("Person2")) {
doSomething(target2);
}
}
Let's say I have the above Publisher
class. It initialises the list
of connection targets by creating spring
beans as follows:
<bean id="publisher" class="com.Publisher">
<constructor-arg>
<list>
<ref bean="target1"/>
<ref bean="target2"/>
</list>
</constructor-arg>
</bean>
In most cases, when main()
method is called, it will use all
as program argument as I expect to send files to both targets. So main()
would call something like this:
pub.publish(target) //target = "ALL"
In that case, I am working with 2 connection objects.
However, in certain scenario, I want to republish
files to a specified target only, so my main()
method will call publish with specified target:
pub.publish(target) //target = "Person1"
In this case, I still end up with multiple connection objects even though only target 1
is necessary for re-publishing.
is there a better approach to writing this for re-publishing? How should I match Program argument (target) to the appropriate connection object? I may also end up having more targets in future and this piece of code is hard coding the targets. is there a better alternative?
Aucun commentaire:
Enregistrer un commentaire