Why @Autowired is null ?

Sun, Sep 18, 2022

Read in 1 minutes

Why We need @autowired ?

When you want spring container to automatically create object for you , you will use @autowired annotation.

Null scenario :

Consider the following scenario. Third party package has class ViewRecords.java . And inside the ViewRecords.java , we have constructor,

ViewRecords(final Audio audio)

Here inside the class contructor , we have one more class.So When I did @Autowired ViewRecords in my class (myclass.java) ,it throws null pointer exception.

Reason for NullPointer Exception :

Spring couldn’t find out the bean for the type Audio (Audio.java) which is passed inside the constructor of ViewRecords.java. So we got nullpointer exception.

Solution : 1

I added the below configuration in the springconfig.xml to solve the nullpointer exception.


	<bean id ="veiwrecords" class="com.demo.VeiwRecords.java>
	<Constructor-arg  ref = "audio">
    <bean id ="audio" class = "com.demo.audio">

Solution : 2

	@Bean("audio")
	@Qualifier("audio")
	Public ViewRecord veiwRecord(){
	Retrun new ViewRecords(new Audio());

Conclusion :

If you try to Autowire a class and that internally has any class (type) which is not managed by spring container , you will get ‘nullpointer’ Exception. So, to solve that problem , you need to enable a bean and then the spring container will get idea about that bean.