Prev Next

Spring / Spring Beans

1. What are Beans in Spring framework? 2. What does a Spring Bean definition consists of? 3. Different Spring Bean Scope. 4. How do I provide beans configuration metadata to the Spring Container? 5. How do I define the scope of a bean in spring framework? 6. Describe the lifecycle of a Bean in Spring framework. 7. Is a singleton bean thread safe in Spring Framework? 8. Explain the important life-cycle methods of a bean in Spring framework. 9. Explain inner beans in Spring framework? 10. What are the limitations of autowiring in Spring framework? 11. How do I inject java.util.Properties into a Spring Bean? 12. Explain @Required annotation in Spring framework. 13. Explain @autowired annotation in spring framework. 14. How do I make autowired bean property as optional? 15. What is @Resource annotation in Spring framework? 16. How do I configure a bean in my spring application? 17. What kind of exception does spring DAO classes throw? 18. Explain the different ways to configure a Java class as Spring Bean. 19. Difference between id and name attribute of <bean> element in a Spring configuration file. 20. Is Spring Bean with singleton scope thread safe? 21. Difference between @Resource and @Autowired in Spring framework. 22. Explain lazy-init attribute of bean tag in Spring. 23. Can we fetch the inner bean from spring container using its id, if an inner bean defines one? 24. Explain Spring bean inheritance. 25. What is Bean Definition Template in Spring framework? 26. What is spring bean pure inheritance template? 27. Can a spring bean tag with no id or name attribute be created? 28. Can spring bean autowire on primitive types? 29. How do I create a stateful bean in Spring framework? 30. Difference between request and prototype bean scope in spring? 31. What is the role of a Spring bean configuration file? 32. Explain Circular Dependency scenario in Spring. 33. Spring Bean marked as abstract by abstract=true needs the corresponding java class be abstract ? 34. Spring Bean: Specify particular implementation of collection in your bean definition. 35. Spring bean: difference between stateless and stateful beans. 36. Can I define spring bean twice with same name in different bean definition file? 37. Can I define spring bean twice with the same bean id in same file? 38. Explain JSR-250 annotation. 39. What is primary annotation in Spring? 40. How to get all the Spring beans implementing a specific interface? 41. What are the attributes of Spring @Transactional annotation? 42. When is a spring bean destroy-method being called? 43. When is a Spring Singleton bean garbage collected? 44. When is a prototype bean garbage collected? 45. Explain BeanPostProcessor beans. 46. Explain no autowiring mode in spring bean. 47. How do you debug Spring configuration? 48. What is component scan in Spring framework? 49. What happens when a singleton bean contains a prototype bean? 50. What happens when a prototype bean has a singleton dependency? 51. Can a singleton bean hold a request- or session-scoped bean? 52. How does Spring handle @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS) internally? 53. What are the possible issues with prototype beans in singleton beans? 54. What are "Scope Mismatch" errors? 55. Can we inject a session-scoped bean into a prototype bean? 56. Explain @Lookup annotation usage in this context. 57. When should you use prototype scope vs request scope? 58. What is the default scope in Spring and why? 59. How do you ensure each user session gets a unique bean instance even if it's injected into a singleton service? 60. What happens if you call ApplicationContext.getBean() for a prototype bean multiple times? 61. What are the best practices for using prototype scope? 62. Explain the Scope Injection problem and provide a solution to fix it.

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. These beans are created using the configuration metadata definition supplied to the container, for example, in the form ...

Read full answer

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.

Read full answer

3. Different Spring Bean Scope.

1. singleton : Returns a single bean instance per Spring IOC container.(default scope) 2. prototype : Returns a new bean instance each time when requested. 3. request : Returns a single bean instance per HTTP request. 4. session : Returns a single bean instance per HTTP session. 5. global session...

Read full answer

4. 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. Annotation-based configuration. Java-based configuration.

Read full answer

5. 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. The scope attribute takes one of the five values: singleton, prototype, request, session and global session .

Read full answer

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. Once spring container created the bean, Spring bean factory will contro...

Read full answer

7. Is a singleton bean thread safe in Spring Framework?

No. The singleton scoped beans are not thread-safe in Spring framework.

Read full answer

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. The teardown method which is invoked when the bean is unloaded from the container. The bean XML tag has two important attributes init-method and destroy-method to define your custom i...

Read full answer

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 element inside the or elements of a bean definition to declare inner beans. Inner beans are always anonymous and it...

Read full answer

10. What are the limitations of autowiring in Spring framework?

Overriding: You can still specify dependencies using and settings which will always override autowiring. Primitive data types: You cannot autowire simple properties such as primitives. Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.

Read full answer

11. How do I inject java.util.Properties into a Spring Bean?

tag can be used to inject properties to a spring bean as shown below.

Read full answer

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 Employe...

Read full answer

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. Autowired annotation on s...

Read full answer

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.

Read full answer

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 which w...

Read full answer

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.

Read full answer

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 .

Read full answer

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. The bean element tag is used in xml context file to configure a Spring Bean. Using Java Based Configuration , you can configure a Spring bean using @Bean annotation. This annotatio...

Read full answer

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 characters . Special characters like #, @, $, *, / are ...

Read full answer

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. Hence in default mode spring beans are not thread-safe .

Read full answer

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.

Read full answer

22. Explain lazy-init attribute of bean tag in Spring.

lazy-init attribute of 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. To make ApplicationContext to initialize the all the spring b...

Read full answer

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 .

Read full answer

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. A child bean can be configured using parent attribute on bean tag, parent bean id as its value. A child bean definition inherits c...

Read full answer

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 attribute with its value as true. The p...

Read full answer

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.

Read full answer

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. So it does not require an id or name attribute as they are not referenced.

Read full answer

28. Can spring bean autowire on primitive types?

No . @Autowired annotation expects a bean of the type to present in the applicationContext.

Read full answer

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.

Read full answer

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. So in a HttpRequest, if the getBean method is called twice on Application and there will be only one bean instantiated ...

Read full answer

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. Once the context is initialized, it can be used to get different bean instan...

Read full answer

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 into each other, the Spring IoC container detects this circular...

Read full answer

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.

Read full answer

34. Spring Bean: Specify particular implementation of collection in your bean definition.

and 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. Note that util tag has id attribute as well to refer ...

Read full answer

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. These beans are created while the ApplicationContext is being initialized. The SAME bean instance will be returned/injected during the lifetime of this ApplicationContext. . state...

Read full answer

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. The main objective of this behavior is to ovrrride the previously loaded bean definition. This behavior is configurable; DefaultListableBeanFactory allows to control this behavior using setAllowBeanD...

Read full answer

37. Can I define spring bean twice with the same bean id in same file?

No. It is not possible.

Read full answer

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. @PreDestroy defines the method to be invoked post the bean destruction event. @Resource wires the bean using name autowi...

Read full answer

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 . utilRepository = ut...

Read full answer

40. How to get all the Spring beans implementing a specific interface?

Using ApplicationContext.getBeansOfType method we can retrieve all the beans implementing a specific interface. Usage : ApplicationContext . getBeansOfType ( YourClass . class ); package net.javapedia.spring.beanoftype.example; import java.util.Map; import org.springframework.context.annotation.A...

Read full answer

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.

Read full answer

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...

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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. Based on the required module, logging could be expanded.Use either or c...

Read full answer

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 it as Spring controller.

Read full answer

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. @Component @Scope ( "singleton" ) public class SingletonBean { @Autowired private PrototypeBean prototypeBean; public void show() { System . ...

Read full answer

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).

Read full answer

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. @Component @Scope (value = WebApplicationContext . SCOPE_REQUEST, proxyMode = ScopedProxyMode . TARGET_CLASS) public class RequestBean {} @Component @Scope ( "singleton" ) public class SingletonBean { ...

Read full answer

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).

Read full answer

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. Solution: Use lookup method injection or ObjectFactory.

Read full answer

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

Read full answer

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 = ...).

Read full answer

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 } }

Read full answer

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.

Read full answer

58. What is the default scope in Spring and why?

Singleton is default because it improves performance and memory efficiency -most beans are stateless.

Read full answer

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) .

Read full answer

60. What happens if you call ApplicationContext.getBean() for a prototype bean multiple times?

A new instance is created each time.

Read full answer

61. What are the best practices for using prototype scope?

Only when truly needed; otherwise prefer stateless singleton beans.

Read full answer

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 instance. This is common fo...

Read full answer

«
»

Comments & Discussions