is spring framework 3.0 type-safe
-
10-10-2019 - |
سؤال
In another question I asked, raised a concern that spring framework is not type safe. Is it true, or fixed, and can you give an example what it means exactly?
المحلول
First of all, what does "type-safe" mean for a dependency injection framework. What I can think of is that you can get a bean from the context by specifying a type, and not just a bean name. Spring 3 allows this.
Otherwise, type-safety means that when you can define your dependencies by their type. And you can do this in all versions of spring.
Another thing is compile-time safety. With spring pre-3.0 when you had to differentiate between two beans that share the same interface (or supertype) by using their string-based name. In spring 3.0 you can use annotation-based qualifiers (using javax.inject.Qualifier
), so it is compile-time safer as well.
Another thing to mention is the use of generics. You can have, for example @Inject List<MyService>
in spring.
نصائح أخرى
Define a custom annotation using @Qualifier
To identify the injected bean without specifying the name, we need to create a custom annotation. This is an equivalent procedure to the use of JSR 330 annotations(Inject) in CDI.
@Target({ElementType.Field, ElementType.Parameter})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @Interface Student {
}
Now assign this custom annotation to implementation of EntityDao Interface
@Component
@Student
public class StudentDao implements EntityDao {
}
@Component tells Spring that this a bean definition. @Student annotation is used by Spring IoC to identify StudentDao as EntityDao's implementation whenever reference of EntityDao is used. Inject the bean using @Autowired and custom qualifier Something like this.
@Autowired
@Student
private EntityDao studentDao; // So the spring injects the instance of StudentDao here.
This makes less use of String-names, which can be misspelled and are harder to maintain. - I find this post very useful. http://www.coolcoder.in/2011/08/how-to-use-type-safe-dependency.html
It depends on how you use it and what you mean by type-safe (see Bozho's answer for more info on the latter): if you use the xml config to produce your beans, then you're probably type-safe after start-up.
However, if you use the new Java Bean config (which has its own limitations) you get compile-time safety.
I'm not advocating the latter over the former, but it's something to consider.