开发者

Removing type checking by using Spring bean id's

开发者 https://www.devze.com 2023-01-25 09:26 出处:网络
I\'ve written a state machine for navigating an automated telephone system, where each state is represented by its own Java class file, for a total of 50+ classes. Rather than write the instantiation

I've written a state machine for navigating an automated telephone system, where each state is represented by its own Java class file, for a total of 50+ classes. Rather than write the instantiation and factory code myself, I decided to use Spring for bean definition and dependency injection. This works fine, however I have lost compile-time type checking by moving from:

State next = getState(Instructions.class);

to

ApplicationContext ctx = ...
State next = ctx.getBean("instructions", State.class);

Instead of having compiler checks that I've specified a real, existing state, I now have to rely on the id being spelled properly in both my source code and the bean xml.

Is there a better way to do this? I haven't worked extensively with Spring since early 2.0 days, so I don't have much real world experience to draw on. What are the drawbacks and advantage开发者_C百科s of this approach? Is there is something extra I could to to verify proper id strings are used?


Consider using Spring autowiring and in your class have:

class StateMachine
{
    @Autowired
    State next;
}

You can also use qualifiers to select amongst the different implementation you may have of State.


Turn off lazy initialization of Spring, and you'll at least cure the type safety department. You could also consider a 'grand central station' bean into which all of the states are inserted by name, this resulting in a yell if any go missing. You can still mispell in your Java code.


I would personally go about it one of two ways:

1) If only a few states needed access to a few other states, I would inject those directly (like Steve said in his answer):

@Inject
public setInstructions(Instructions instructions) { ... }

2) On the other hand, if any state needs access to any other one, no one wants to inject the other 49 states into each of the 50 classes, so I would have one central class that had all 50 injected and basically build my state machine in that class.

Spring really is a factory when it comes down to it, but tying yourself to the Spring API kind of goes against their philosophy, and as you mentioned, you lose type safety.

0

精彩评论

暂无评论...
验证码 换一张
取 消