Search code examples
springspring-annotations

Use Spring annotation to inject dependency


In my project, i see a spring dependency inujection syntax like this in my integration layer:

applicationContext.getBean("beanName");

where applicationContext instance of ClasspathXMLApplicationContext and "beanName" is defined in the spring xml. If I want to inject it with Annotation, which one should I use? @Inject,@Autowired,@Resource. Seems like I cna use any one of these and I cannot seem to be able to decide which one. This is SPring integration layer , not MVC layer but i dont think that makes any difference.


Solution

  • @Inject and @Autowired do the same thing, it autowires by type. @Inject is preferred because it is a java annotation and does not couple you to Spring

    @Resource autowires by name. This is useful when you have many beans of the same type. You can also use @Named along with @Inject for the same behavior.