3

I am new to spring .

I have understood the @Autowired annotation and in order to use it. i have learnt that we should use 1)context:annotation-config or 2)AutowiredAnnotationBeanPostProcessor. But when I saw a sample project I did not find anything so is it mandatory to use the above mentioned things.


I am thinking that @Autowired annotation will create the objects when we deploy our web.xml in the server because in standalone application when i have tested we are using public static void main(String[] args) to invoke the bean class.But in the web project we don't have anything like that so when we deploy our web.xml in the server or application.xml which contains spring configurations objects will get created.

Is my understanding correct in the above 2 imaginations.

Please help me.

alexbt
  • 16,415
  • 6
  • 78
  • 87
jack0989
  • 39
  • 2

1 Answers1

1

When using xml file, you need to add the PostProcessor Bean for respective dependeny. You can skip this if you use

 <context:annotation-config/>

This would mean that you do not need to add any annotationPostProcessors. This would include all of them.

Secondly, when you use Autowire annotation, you are auto-wiring by type. You are telling spring that during initialization set the value of this field.

Normally what you need to do is that in the application main,

  1. Get the applicationContext.
  2. Using ApplicationContext, get the requiredBean from XML.
  3. Set the bean in your service class.

You can skip these steps by Autowiring the bean in your service class.Let me know if you understood this.

Prateek Mishra
  • 1,226
  • 10
  • 21
  • thanks for the explanation, first one i have understood, but for the second .yes we have those 3 steps in standalone applicationswhich you have told .but in the web project i have only autowired and i am not getting any applicationcontext,and getting the required bean and all that stuff.the only thing i am doing is that – jack0989 Apr 21 '17 at 07:10
  • @autwired private Employee employee; employee.findEmployeeByid(Long Id); so i wanted to know when this object gets created.Will it get created at the time deploying this in to the server.(web.xml or applicationcontext.xml) – jack0989 Apr 21 '17 at 07:14
  • I suppose this Employee is a spring repository and you are auto-wiring this to get data from some entity class. So, when you start your application, at that time all service, repository, component, classes are called by spring. At this time the object is set. So when you deploy and start your servlet container, all autowired dependencies are set. – Prateek Mishra Apr 21 '17 at 07:22
  • Does this answer your question ? – Prateek Mishra Apr 21 '17 at 07:28
  • Thanks prateeek Mishra – jack0989 Apr 21 '17 at 07:29