Skip to content

Instantly share code, notes, and snippets.

@jaideepjagyasi
Last active February 26, 2020 17:20
Show Gist options
  • Save jaideepjagyasi/9c39b8892be1a2f01fe7643c16d3eb54 to your computer and use it in GitHub Desktop.
Save jaideepjagyasi/9c39b8892be1a2f01fe7643c16d3eb54 to your computer and use it in GitHub Desktop.
FAQ: Why do we specify the Coach interface in getBean()?
Question
Why do we specify the Coach interface in getBean()?
For example:
Coach theCoach = context.getBean("myCoach", Coach.class);
---
Answer
When we pass the interface to the method, behind the scenes Spring will cast the object for you.
context.getBean("myCoach", Coach.class)
However, there are some slight differences than normal casting.
From the Spring docs:
Behaves the same as getBean(String), but provides a measure of type safety by throwing a BeanNotOfRequiredTypeException if the bean is not of the required type. This means that ClassCastException can't be thrown on casting the result correctly, as can happen with getBean(String).
Source: http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/BeanFactory.html#getBean-java.lang.String-java.lang.Class-
=======================
FAQ: What is the purpose for the no arg constructor?
FAQ: What is the purpose for the no arg constructor?
Question:
I was wondering why you created a no arg constructor? I thought that they are implied by Java and only required when you also have an overloaded constructor. Or is this a Spring specific thing?
---
Answered by: Oleksandr Palamarchuk
When you don’t define any constructor in your class, compiler defines default one for you, however when you declare any constructor (in your example you have already defined a parameterized constructor), compiler doesn’t do it for you.
Since you have defined a constructor in class code, compiler didn’t create default one. While creating object you are invoking default one, which doesn’t exist in class code. Then the code gives an compilation error.
===================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment