Spring / Spring Beans
1. What are Beans in Spring framework?
The Spring Beans are nothing but Java Objects that forms the backbone of a Spring application. Those beans are instantiated, assembled, and managed by the Spring IoC container....
2. What does a Spring Bean definition consists of?
A Spring Bean definition holds all the configuration metadata required for the container to understand how to create a bean, manage its lifecycle and its dependencies.
3. Different Spring Bean Scope.
1. singleton : Returns a single bean instance per Spring IOC container.(default scope) 2....
4. How do I define the scope of a bean in spring framework?
While defining a bean in Spring xml configuration, the scope also can be declared for the bean. The scope attribute of the bean defines its scope....
5. How do I provide beans configuration metadata to the Spring Container?
There are 3 ways to provide configuration metadata to the Spring Container. XML based configuration file.
6. Describe the lifecycle of a Bean in Spring framework.
The spring container loads the bean definition from the XML file and instantiates the bean. Also it initializes the properties of the bean using Dependency Injection (DI) that are specified in the bean definition in XML file....
7. Is a singleton bean thread safe in Spring Framework?
8. Explain the important life-cycle methods of a bean in Spring framework.
There are 2 important bean lifecycle methods. The setup method called when the bean is loaded into the container....
9. Explain inner beans in Spring framework?
Inner beans are spring beans that are used as a property of another spring bean. Spring's XML-based configuration metadata provides the use of <bean/> element inside the <property/> or <constructor-arg/> elements of a bean definition to declare inner beans....
10. What are the limitations of autowiring in Spring framework?
Autowiring fails on primitives, multiple same-type beans without @Qualifier, and circular constructor dependencies. It also cannot inject final fields without a constructor.
11. How do I inject java.util.Properties into a Spring Bean?
<props> tag can be used to inject properties to a spring bean as shown below.
12. Explain @Required annotation in Spring framework.
The @Required annotation applies to bean property setter methods and it indicates that the represented bean property is required and must be initialized in XML configuration file at configuration time otherwise the container will throw a BeanInitializationException exception. public class...
13. Explain @autowired annotation in spring framework.
The @Autowired annotation provides fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire a bean on the setter method, constructor, a property or methods with arbitrary names and/or multiple arguments....
14. How do I make autowired bean property as optional?
By default, the @Autowired annotation sets the dependency as mandatory similar to @Required annotation, however, the default behavior can be turned off by using required = false option with @Autowired.
15. What is @Resource annotation in Spring framework?
javax.annotation.@Resource annotation can be applied on fields or setter methods for dependency injection and it follows by-name autowiring semantics, name extracted from the name of the annotated setter/field or from the 'name' attribute. The @Resource annotation takes a 'name' attribute...
16. How do I configure a bean in my spring application?
Using bean xml tag, a spring bean can be configured. Bean tag has id attribute that specifies the bean name and the class attribute represents the fully qualified class name.
17. What kind of exception does spring DAO classes throw?
The spring DAO class do not throw any specific exceptions such as SQLException instead it throws exceptions that are subclasses of DataAccessException .
18. Explain the different ways to configure a Java class as Spring Bean.
There are 3 different ways to configure a class as Spring Bean. XML Configuration is the most popular configuration....
19. Difference between id and name attribute of <bean> element in a Spring configuration file.
Per the Spring 3 documentation, 'you use the id and/or name attributes to specify the bean identifier(s)'. The name attribute behaves and functions similar to id attribute on a bean but it allows the bean unique identifier to contain special...
20. Is Spring Bean with singleton scope thread safe?
The default scope of Spring bean is singleton, which means that there be only one instance per context. Having a bean class level variable that any thread can update will lead to inconsistent data....
21. Difference between @Resource and @Autowired in Spring framework.
@autowired wires by bean type whereas @resource wires by name. Using @Qualifier along with the @Autowired functions exactly similar to the @Resource annotation.
22. Explain lazy-init attribute of bean tag in Spring.
lazy-init attribute of <bean> tag is used to specify whether a spring bean is to be lazily initialized or not. BeanFactory initializes all the spring beans lazily while ApplicationContext initializes all singleton spring beans eagerly....
23. Can we fetch the inner bean from spring container using its id, if an inner bean defines one?
No. An inner bean cannot be accessed even if the id attribute is defined, getBean ("theInnerId") will fail with NoSuchBeanDefinitionException .
24. Explain Spring bean inheritance.
Spring bean can exhibit inheritance behavior by defining parent and child beans. The parent beans are configured using the abstract attribute value being set to true....
25. What is Bean Definition Template in Spring framework?
Bean definition template also referred as parent beans can be used to define common bean definitions shared by other child beans without redefining it. While defining a Bean Definition Template, class attribute may not be defined and should specify abstract...
26. What is spring bean pure inheritance template?
The spring bean definition with abstract attribute as true with no class attribute are meant for only inheritance and sharing of properties that are termed as pure definition template.
27. Can a spring bean tag with no id or name attribute be created?
Yes. Some spring beans are not required to be accessed by any other beans in the context file or by programmatically.
28. Can spring bean autowire on primitive types?
No . @Autowired annotation expects a bean of the type to present in the applicationContext.
29. How do I create a stateful bean in Spring framework?
Using the prototype bean scope, one can define a stateful bean. Prototype scoped beans are instantiated every time it is requested.
30. Difference between request and prototype bean scope in spring?
Prototype scope creates a new instance everytime getBean method is invoked on the ApplicationContext. Whereas for request scope, only one instance is created for an HttpRequest....
31. What is the role of a Spring bean configuration file?
The Spring bean configuration file defines all the beans that will be initialized by Spring Context. When an instance of Spring ApplicationContext is created, it reads the spring bean xml file and initialize all of them....
32. Explain Circular Dependency scenario in Spring.
Consider a scenario where Class A requires an instance of class B through constructor injection, and class B requires an instance of class A through constructor injection. If you configure beans for the classes A and B to be injected...
33. Spring Bean marked as abstract by abstract=true needs the corresponding java class be abstract ?
No, not necessarily. A spring bean marked as abstract cannot be instantiated, repurpose this bean reference as parent to other child bean definition.
34. Spring Bean: Specify particular implementation of collection in your bean definition.
<util:set> <util:list> and <util:map> tag specifies the collection for the spring bean and the set-class property of the tag specifies the particular implementation of collection class you prefer. <util:list set-class= "java.util.LinkedList" > Note that util tag has id attribute as...
35. Spring bean: difference between stateless and stateful beans.
stateless beans : beans that are singleton and are initialized only once. The only state they have is a shared state....
36. Can I define spring bean twice with same name in different bean definition file?
Yes. When the second bean definition file loads, it overrides the definition from the first file....
37. Can I define spring bean twice with the same bean id in same file?
No. It is not possible.
38. Explain JSR-250 annotation.
Spring supports JSR 250 annotations that includes @PostConstruct, @PreDestroy and @Resource annotation. @PostConstruct defines the callback method post the bean initialization.
39. What is primary annotation in Spring?
primary annotation sets the bean to get preference when multiple candidates are qualified to auto-wire a single-valued dependency. @Component public class UtilService { private UtilRepository utilRepository; @Autowired public UtilService(UtilRepository utilRepository) { this .
40. How to get all the Spring beans implementing a specific interface?
Call ApplicationContext.getBeansOfType(YourInterface.class) to get every Spring bean that implements the interface, keyed by bean name.
41. What are the attributes of Spring @Transactional annotation?
Spring transactions take the following properties, propagation level, isolation, timeout, rollback rules and read-only for any transaction.
42. When is a spring bean destroy-method being called?
Spring bean destroy method is called when the app-context is closed by calling close method or by calling registerShutdownHook method. /Getting application context ApplicationContext appContext = new ClassPathXmlApplicationContext(beansXMLConfig); //cleaning context ( (ClassPathXmlApplicationCont
43. When is a Spring Singleton bean garbage collected?
Singleton beans are created when the Spring container starts and are destroyed when the Spring container stops . The reason is spring container always maintains a reference to it while it is also manually referenced anywhere in your code.
44. When is a prototype bean garbage collected?
Spring does only care for the creation and configuration of the prototype bean and then its the responsibility of the user (or the JVM) to do whatever is necessary. Spring does NOT keep internal references to prototype beans.
45. Explain BeanPostProcessor beans.
BPP beans are a special kind of beans that get created before any other beans and interact with newly created beans. To create a bean post processor, implement the BeanPostProcessor interface and implement postProcessBeforeInitialization () and postProcessAfterInitialization () methods.
46. Explain no autowiring mode in spring bean.
no is the default setting which means no autowiring and you should use explicit bean reference for wiring.
47. How do you debug Spring configuration?
The quick way would be enabling the spring logging in log4j. Add spring appenders to the log4j config either log4j.xml or log4j.properties....
48. What is component scan in Spring framework?
Component Scan tells Spring the packages containing annotated classes that should be managed by Spring. If you have a class annotated with @Controller which is in a package, if not scanned by Spring, you will not be able to use...
49. What happens when a singleton bean contains a prototype bean?
The prototype bean is created only once, when the singleton is created. This means you won't get a new prototype instance every time the singleton uses it....
50. What happens when a prototype bean has a singleton dependency?
The singleton is injected once into each prototype. Each prototype gets the same singleton instance (as expected).
51. Can a singleton bean hold a request- or session-scoped bean?
Not directly, it would cause a scope mismatch. You'll get an error unless you use a proxy mode....
52. How does Spring handle @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS) internally?
Spring creates a CGLIB proxy around the target bean. When the bean is accessed, the proxy looks up the actual scoped bean from the current context (request/session).
53. What are the possible issues with prototype beans in singleton beans?
State inconsistency: one prototype instance is reused. Hidden memory leaks if not managed.
54. What are "Scope Mismatch" errors?
When a narrower scope bean (e.g., request) is injected into a wider scope bean (e.g., singleton) without proxy, Spring throws: BeanCreationException: Scope 'request' is not active for the current thread
55. Can we inject a session-scoped bean into a prototype bean?
Yes, but you'll likely need proxying because the prototype bean might live outside of an HTTP session context. Normally, you'd still use @Scope(, proxyMode = ).
56. Explain @Lookup annotation usage in this context.
Marks a method for method injection Spring overrides it dynamically to return a new instance. @Component public class SingletonBean { @Lookup public PrototypeBean getPrototypeBean() { return null; // overridden by Spring } }
57. When should you use prototype scope vs request scope?
Prototype: For backend/service components where you manually manage lifecycle. Request: For web-specific beans tied to HTTP requests.
58. What is the default scope in Spring and why?
Singleton is default because it improves performance and memory efficiency -most beans are stateless.
59. How do you ensure each user session gets a unique bean instance even if it's injected into a singleton service?
Use @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) .
60. What happens if you call ApplicationContext.getBean() for a prototype bean multiple times?
A new instance is created each time.
61. What are the best practices for using prototype scope?
Only when truly needed; otherwise prefer stateless singleton beans.
62. Explain the Scope Injection problem and provide a solution to fix it.
Injecting longer-lived into shorter-lived : This works as expected. For example, injecting a singleton bean (which is created once for the entire application) into a prototype bean (new instance for each request) means all prototype instances share the single singleton...