Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DIfference between @Autowired and New Keword and Application context to create a object

Tags:

java

spring

Please any one tell me the difference between

@Autowired
CustomerService cService;

And

CustomerService cService=new CustomerService();

And

private static  ApplicationContext applicationContext;
DefaultValueBean defaultValueBean = (DefaultValueBean) applicationContext.getBean("defaultValue");

2 Answers

The difference between doing CustomerService cService=new CustomerService(); and the other two statements is that in the later two statements, Spring will manage the lifecyle of the created object and it's dependencies whereas in the former case, you will have to manage the lifecycle of your object and all the dependencies it needs.

The difference between doing @Autowired CustomerService cService; and DefaultValueBean defaultValueBean = (DefaultValueBean) applicationContext.getBean("defaultValue"); is that in the former case,Spring will look for a bean depending on the autowiring mode where as in the later, you ask Spring to look for a bean whose idis configured as defaultValue

You can go through the Spring documentation on dependency injection for a more detailed explanation.

like image 55
Chetan Kinger Avatar answered Sep 04 '25 19:09

Chetan Kinger


From what I understand when you declare a bean using Autowire in spring, you are accessing an instance of that object that would be available from the systems start up. So if you were to access it in two different classes you would be accessing the same object.

CustomerService cService=new CustomerService();

is declaring a completely new instance of that object so if you were to do this in two different classes then they would both be totally separate objects.

for example

public class Class1(){ 
@Autowired
CustomerService cService;
} 

public class Class2(){
@Autowired
CustomerService cService;
}

public class Class3(){
CustomerService cService=new CustomerService();
}

Class1 and Class2 are both accessing exactly the same object whereas Class3 is accessing a completely new instance of this object.

Your final way of declaring the bean like Chetan Kinger explains does the same as the Autowiring in that the lifecycle is managed by spring the only difference is in how the bean is being located.

this site helped me a lot when I first came across spring (may bee helpful to you too) http://www.tutorialspoint.com/spring/index.htm

like image 33
Leanne Avatar answered Sep 04 '25 19:09

Leanne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!