Thursday, August 11, 2011

Dependency Injection in Java - @Resource, @Inject or @Autowired?

The @Resource documentation states that the "name" attribute refers to "The JNDI name of the resource". Spring has overloaded this to mean that you can refer to bean identifiers… but as far as the Java spec goes, there's no contractual obligation for a resource name to refer to a bean id. @Resource referring to Spring bean ids is therefore quite Spring-specific.

@Autowired is Spring specific.

@Inject is not Spring specific and performs type-safe injection.

The other benefit you'll get from type-safe injection is the ability to safely re-factor within your favourite IDE, but I personally think that the contractual obligation mentioned above is more important.

 

No comments: