What is Spring AOP?
Aspect oriented Programming is programming paradigm which is analogous to object oriented programming. Key unit of object oriented programming is class, similarly key unit for AOP is Aspect. Aspect enable modularisation of concerns such as transaction management, it cut across multiple classes and types. It also refers as a crosscutting concerns.
What is Spring AOP?
Aspect oriented Programming is programming paradigm which is analogous to object oriented programming. Key unit of object oriented programming is class, similarly key unit for AOP is Aspect. Aspect enable modularisation of concerns such as transaction management, it cut across multiple classes and types. It also refers as a crosscutting concerns.
What is Aspect, Advice, Join point and pointcut in Spring AOP?
Aspect: An Aspect is a class that implements concerns that cut across different classes such as logging. It is just a name.
Joint Point : It is a point in execution of program such as execution of method. In Spring AOP, a join point always represents a method execution.
Advice : Action taken by aspect at particular join point. For example: Before execution of getEmployeeName() method, put logging. So here, we are using before advice.
Pointcut : Pointcut is an expression that decides execution of advice at matched joint point. Spring uses the AspectJ pointcut expression language by default.
Example : https://www.javainuse.com/spring/spring-boot-aop
What is @Qualifier annotation in Spring?
You can have more than one bean of same type in your XML configuration but you want to autowire only one of them ,so @Qualifier removes confusion created by @Autowired by declaring exactly which bean is to autowired.
What is @Required annotation in Spring?
This annotation simply indicates that the affected bean property must be populated at configuration time: either through an explicit property value in a bean definition or through autowiring. The container will throw an exception if the affected bean property has not been populated; this allows for eager and explicit failure, avoiding NullPointerExceptions or the like later on.
Suppose you have very large application and you get NullPointerExceptions because required dependency has not been injected then it is very hard to find out what goes wrong.So this annotation helps us in debugging the code.
Circular dependencies in Spring
For example: Class A requires an instance of Class B and Class B requires an instance of Class A.
As you can see, we are getting BeanCurrentlyInCreationException.Requested bean is currently in creation: Is there an unresolvable circular reference?
Solution
Setter injection
You use @Lazy with @Autowired to solve circular dependencies in Spring.
public class A {
B b;
@Autowired
public A(@Lazy B b) {
super();
this.b = b;
}
}
You use @PostConstruct with @Autowired to solve circular dependencies in Spring.
@PostConstruct
public void init()
{
b.setA(this);
}
What happens when you inject prototype bean into singleton bean? Can you explain the behavior?
When you inject prototype bean to singleton bean, prototype bean still behave like a singleton bean.
Solution
There are many ways to solve this problem.
Using Method injection
@Lookup
public Y getY() {
return y;
}
You can use method injection to solve this problem.Simply use @Lookup with getY() method, it will return new instance each time.
Spring will use CGLIB to generate dynamically a subclass that overrides the method getY(). It then registers the bean into the application context. Whenever we request for getY() method, it will return new instance of Class Y.
There are two options here, either create dummy method or mark method as abstract. When you mark method as abstract, then you will have to declare class abstract as well, hence we have used dummy method in this scenario.
Using ObjectFactory
You can use ObjectFactory to get new object each time getY() method is called.
@Autowired
private ObjectFactory<Y> prototypeBeanObjectFactory;
Y y;
public Y getY() {
return prototypeBeanObjectFactory.getObject();
}
Using ApplicationContextAware
You can return new bean using application context wheneven getY() method is getting called.
public class X implements ApplicationContextAware{
private ApplicationContext applicationContext;
Y y;
public Y getY() {
return applicationContext.getBean(Y.class);
}
public void setY(Y y) {
this.y = y;
}
@Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException {
this.applicationContext=arg0;
}
}
Link : https://java2blog.com/spring-interview-questions-and-answers/
What is the difference between Bean Factory and ApplicationContext?
BeanFactory is also called basic IOC and ApplicationContext is called Advanced IOC. Although BeanFactory and ApplicationContext both are used to get the beans from IOC container by using method getBean(String beanName). But they have some significant differences in their implementation which are described as below :
BeanFactory uses lazy initialization approach whereas ApplicationContext uses eager initialization approach.i.e BeanFactory creates a singleton bean only when it is requested from it but ApplicationContext creates all singleton beans at the time of its own initialization.
ApplicationContext supports internationalization but BeanFactory do not.
Annotation based dependency Injection is not supported by BeanFactory whereas ApplicationContext supports using annotation @PreDestroy, @Autowired.
The ApplicationContext interface is built on top of the BeanFactory interface. It adds some extra functionality than BeanFactory such as simple integration with Spring’s AOP, message resource handling (for I18N), event propagation, application layer specific context (e.g. WebApplicationContext) for web application. So it is better to use ApplicationContext than BeanFactory.
In which scenario, you will use singleton and prototype scope?
Singleton scope should be used with EJB stateless session bean and prototype scope with EJB stateful session bean.
Are Singleton beans thread safe in Spring Framework?
No, singleton beans are not thread-safe in Spring framework.
What are some of the important Spring annotations you have used?
Some of the Spring annotations that I have used in my project are:
@Controller – for controller classes in Spring MVC project.
@RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation.
@ResponseBody – for sending Object as response, usually for sending XML or JSON data as response.
@PathVariable – for mapping dynamic values from the URI to handler method arguments.
@Autowired – for autowiring dependencies in spring beans.
@Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type is present.
@Service – for service classes.
@Scope – for configuring scope of the spring bean.
@Configuration, @ComponentScan and @Bean – for java based configurations.
AspectJ annotations for configuring aspects and advices, @Aspect, @Before, @After, @Around, @Pointcut etc
Name some of the design patterns used in Spring Framework?
Spring Framework is using a lot of design patterns, some of the common ones are:
Singleton Pattern: Creating beans with default scope.
Factory Pattern: Bean Factory classes
Prototype Pattern: Bean scopes
Adapter Pattern: Spring Web and Spring MVC
Proxy Pattern: Spring Aspect Oriented Programming support
Template Method Pattern: JdbcTemplate, HibernateTemplate etc
Front Controller: Spring MVC DispatcherServlet
Data Access Object: Spring DAO support
Dependency Injection and Aspect Oriented Programming
What are the types of the transaction management Spring support?
Spring supports two types of transaction management:
Programmatic transaction management: This means that you have managed the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.
Declarative transaction management: This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions.
Which are the important beans lifecycle methods?
https://siddharthnawani.blogspot.com/2019/10/spring-bean-life-cycle.html
How can you inject a Java Collection in Spring?
Spring offers the following types of collection configuration elements:
The <list> type is used for injecting a list of values, in the case that duplicates are allowed.
The <set> type is used for wiring a set of values but without any duplicates.
The <map> type is used to inject a collection of name-value pairs where name and value can be of any type.
The <props> type can be used to inject a collection of name-value pairs where the name and value are both Strings.
What is bean auto wiring?
The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for a bean by inspecting the contents of the BeanFactory without using <constructor-arg> and <property> elements.
Explain different modes of auto wiring?
The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection:
no: This is default setting. Explicit bean reference should be used for wiring.
byName: When autowiring byName, the Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.
byType: When autowiring by datatype, the Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exist, a fatal exception is thrown.
constructor: This mode is similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.
autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.
Are there limitations with autowiring?
Limitations of autowiring are:
Overriding: You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring.
Primitive data types: You cannot autowire simple properties such as primitives, Strings, and Classes.
Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.
Difference between Setter Injection and Constructor Injection
https://codenuclear.com/difference-between-setter-injection-and-constructor-injection/
Are Singleton beans thread safe in Spring Framework?
Spring framework does not do anything under the hood concerning the multi-threaded behavior of a singleton bean. It is the developer’s responsibility to deal with concurrency issue and thread safety of the singleton bean.
While practically, most spring beans have no mutable state (e.g. Service and DAO clases), and as such are trivially thread safe. But if your bean has mutable state (e.g. View Model Objects), so you need to ensure thread safety. The most easy and obvious solution for this problem is to change bean scope of mutable beans from “singleton” to “prototype“.
How do you turn on annotation based autowiring?
<beans>
<context:annotation-config />
</beans>
What are the different types of events in spring framework?
Spring’s ApplicationContext provides the functionality to support events and listeners in code. We can create beans that listen for events which are published through our ApplicationContext. Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. So if a bean implements the ApplicationListener, then every time an ApplicationEvent gets published to the ApplicationContext, that bean is notified.
public class AllApplicationEventListener implements ApplicationListener < ApplicationEvent >
{
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent)
{ //process event
}
}
Spring provides the following 5 standard events:
ContextRefreshedEvent : This event is published when the ApplicationContext is either initialized or refreshed. This can also be raised using the refresh() method on the ConfigurableApplicationContext interface.
ContextStartedEvent : This event is published when the ApplicationContext is started using the start() method on the ConfigurableApplicationContext interface. You can poll your database or you can re/start any stopped application after receiving this event.
ContextStoppedEvent : This event is published when the ApplicationContext is stopped using the stop() method on the ConfigurableApplicationContext interface. You can do required house keeping work after receiving this event.
ContextClosedEvent : This event is published when the ApplicationContext is closed using the close() method on the ConfigurableApplicationContext interface. A closed context reaches its end of life; it cannot be refreshed or restarted.
RequestHandledEvent : This is a web-specific event telling all beans that an HTTP request has been serviced.
Apart from above, you can create your own custom events by extending ApplicationEvent class. e.g.
public class CustomApplicationEvent extends ApplicationEvent
{
public CustomApplicationEvent ( Object source, final String msg )
{
super(source);
System.out.println("Created a Custom event");
}
}
To listen this event, create a listener like this:
public class CustomEventListener implements ApplicationListener < CustomApplicationEvent >
{
@Override
public void onApplicationEvent(CustomApplicationEvent applicationEvent) {
//handle event
}
}
And to publish this event, you will need the help of applicationContext instance.
CustomApplicationEvent customEvent = new CustomApplicationEvent( applicationContext, "Test message" );
applicationContext.publishEvent ( customEvent );
Name some of the design patterns used in Spring Framework?
There are loads of different design patterns used, but there are a few obvious ones:
Proxy – used heavily in AOP, and remoting.
Singleton – beans defined in spring config files are singletons by default.
Template method – used extensively to deal with boilerplate repeated code e.g. RestTemplate, JmsTemplate, JpaTemplate.
Front Controller – Spring provides DispatcherServlet to ensure an incoming request gets dispatched to your controllers.
View Helper – Spring has a number of custom JSP tags, and velocity macros, to assist in separating code from presentation in views.
Dependency injection – Center to the whole BeanFactory / ApplicationContext concepts.
Factory pattern – BeanFactory for creating instance of an object.
Are Singleton beans thread safe in Spring Framework?
No Singleton bean in Spring is not Thread Safe. The two concepts are not even related.
Singletons are about creation. This design pattern ensures that only one instance of a class is created at any point of time. Spring just manage the life cycle of singleton bean and maintains single instance of object.
Thread safety is about execution. Eventually thread safety depends on the code and the code only. And this is the reason why Spring beans are not thread safe.
How to get ServletContext and ServletConfig object in a Spring Bean?
There are two ways to get Container specific objects in the spring bean.
Implementing Spring *Aware interfaces, for these ServletContextAware and ServletConfigAware interfaces.
Using @Autowired annotation with bean variable of type ServletContext and ServletConfig. They will work only in servlet container specific environment only through.
@Autowired
ServletContext servletContext;
How IOC container will create Object for Private constructor classes?
Answer: Spring internally will use reflection API and it will modify the constructor Accessibility and it will create the object of private constructor class also , by using reflection only Spring is doing autowiring and setting the objects into another object.
What are all the AOP advices used in Spring Transaction internally?
Answer: In Spring transaction internally two Advices they used. Before starting the operation it will start the transaction and if operation success it will call commit operation . Here Spring transaction used “Around Advice” and When Saving the Data Error came at that time it will call rollback operation here they used “throws Advice”
Difference between @Component & @Bean
@Component auto detects and configures the beans using classpath scanning whereas @Bean explicitly declares a single bean, rather than letting Spring do it automatically.
@Component does not decouple the declaration of the bean from the class definition where as @Bean decouples the declaration of the bean from the class definition.
@Component is a class level annotation where as @Bean is a method level annotation and name of the method serves as the bean name.
@Component need not to be used with the @Configuration annotation where as @Bean annotation has to be used within the class which is annotated with @Configuration.
We cannot create a bean of a class using @Component, if the class is outside spring container whereas we can create a bean of a class using @Bean even if the class is present outside the spring container.
@Component has different specializations like @Controller, @Repository and @Service whereas @Bean has no specializations.
Aspect oriented Programming is programming paradigm which is analogous to object oriented programming. Key unit of object oriented programming is class, similarly key unit for AOP is Aspect. Aspect enable modularisation of concerns such as transaction management, it cut across multiple classes and types. It also refers as a crosscutting concerns.
What is Spring AOP?
Aspect oriented Programming is programming paradigm which is analogous to object oriented programming. Key unit of object oriented programming is class, similarly key unit for AOP is Aspect. Aspect enable modularisation of concerns such as transaction management, it cut across multiple classes and types. It also refers as a crosscutting concerns.
What is Aspect, Advice, Join point and pointcut in Spring AOP?
Aspect: An Aspect is a class that implements concerns that cut across different classes such as logging. It is just a name.
Joint Point : It is a point in execution of program such as execution of method. In Spring AOP, a join point always represents a method execution.
Advice : Action taken by aspect at particular join point. For example: Before execution of getEmployeeName() method, put logging. So here, we are using before advice.
Pointcut : Pointcut is an expression that decides execution of advice at matched joint point. Spring uses the AspectJ pointcut expression language by default.
Example : https://www.javainuse.com/spring/spring-boot-aop
What is @Qualifier annotation in Spring?
You can have more than one bean of same type in your XML configuration but you want to autowire only one of them ,so @Qualifier removes confusion created by @Autowired by declaring exactly which bean is to autowired.
What is @Required annotation in Spring?
This annotation simply indicates that the affected bean property must be populated at configuration time: either through an explicit property value in a bean definition or through autowiring. The container will throw an exception if the affected bean property has not been populated; this allows for eager and explicit failure, avoiding NullPointerExceptions or the like later on.
Suppose you have very large application and you get NullPointerExceptions because required dependency has not been injected then it is very hard to find out what goes wrong.So this annotation helps us in debugging the code.
Circular dependencies in Spring
For example: Class A requires an instance of Class B and Class B requires an instance of Class A.
As you can see, we are getting BeanCurrentlyInCreationException.Requested bean is currently in creation: Is there an unresolvable circular reference?
Solution
Setter injection
You use @Lazy with @Autowired to solve circular dependencies in Spring.
public class A {
B b;
@Autowired
public A(@Lazy B b) {
super();
this.b = b;
}
}
You use @PostConstruct with @Autowired to solve circular dependencies in Spring.
@PostConstruct
public void init()
{
b.setA(this);
}
What happens when you inject prototype bean into singleton bean? Can you explain the behavior?
When you inject prototype bean to singleton bean, prototype bean still behave like a singleton bean.
Solution
There are many ways to solve this problem.
Using Method injection
@Lookup
public Y getY() {
return y;
}
You can use method injection to solve this problem.Simply use @Lookup with getY() method, it will return new instance each time.
Spring will use CGLIB to generate dynamically a subclass that overrides the method getY(). It then registers the bean into the application context. Whenever we request for getY() method, it will return new instance of Class Y.
There are two options here, either create dummy method or mark method as abstract. When you mark method as abstract, then you will have to declare class abstract as well, hence we have used dummy method in this scenario.
Using ObjectFactory
You can use ObjectFactory to get new object each time getY() method is called.
@Autowired
private ObjectFactory<Y> prototypeBeanObjectFactory;
Y y;
public Y getY() {
return prototypeBeanObjectFactory.getObject();
}
Using ApplicationContextAware
You can return new bean using application context wheneven getY() method is getting called.
public class X implements ApplicationContextAware{
private ApplicationContext applicationContext;
Y y;
public Y getY() {
return applicationContext.getBean(Y.class);
}
public void setY(Y y) {
this.y = y;
}
@Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException {
this.applicationContext=arg0;
}
}
Link : https://java2blog.com/spring-interview-questions-and-answers/
What is the difference between Bean Factory and ApplicationContext?
BeanFactory is also called basic IOC and ApplicationContext is called Advanced IOC. Although BeanFactory and ApplicationContext both are used to get the beans from IOC container by using method getBean(String beanName). But they have some significant differences in their implementation which are described as below :
BeanFactory uses lazy initialization approach whereas ApplicationContext uses eager initialization approach.i.e BeanFactory creates a singleton bean only when it is requested from it but ApplicationContext creates all singleton beans at the time of its own initialization.
ApplicationContext supports internationalization but BeanFactory do not.
Annotation based dependency Injection is not supported by BeanFactory whereas ApplicationContext supports using annotation @PreDestroy, @Autowired.
The ApplicationContext interface is built on top of the BeanFactory interface. It adds some extra functionality than BeanFactory such as simple integration with Spring’s AOP, message resource handling (for I18N), event propagation, application layer specific context (e.g. WebApplicationContext) for web application. So it is better to use ApplicationContext than BeanFactory.
In which scenario, you will use singleton and prototype scope?
Singleton scope should be used with EJB stateless session bean and prototype scope with EJB stateful session bean.
Are Singleton beans thread safe in Spring Framework?
No, singleton beans are not thread-safe in Spring framework.
What are some of the important Spring annotations you have used?
Some of the Spring annotations that I have used in my project are:
@Controller – for controller classes in Spring MVC project.
@RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation.
@ResponseBody – for sending Object as response, usually for sending XML or JSON data as response.
@PathVariable – for mapping dynamic values from the URI to handler method arguments.
@Autowired – for autowiring dependencies in spring beans.
@Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type is present.
@Service – for service classes.
@Scope – for configuring scope of the spring bean.
@Configuration, @ComponentScan and @Bean – for java based configurations.
AspectJ annotations for configuring aspects and advices, @Aspect, @Before, @After, @Around, @Pointcut etc
Name some of the design patterns used in Spring Framework?
Spring Framework is using a lot of design patterns, some of the common ones are:
Singleton Pattern: Creating beans with default scope.
Factory Pattern: Bean Factory classes
Prototype Pattern: Bean scopes
Adapter Pattern: Spring Web and Spring MVC
Proxy Pattern: Spring Aspect Oriented Programming support
Template Method Pattern: JdbcTemplate, HibernateTemplate etc
Front Controller: Spring MVC DispatcherServlet
Data Access Object: Spring DAO support
Dependency Injection and Aspect Oriented Programming
What are the types of the transaction management Spring support?
Spring supports two types of transaction management:
Programmatic transaction management: This means that you have managed the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.
Declarative transaction management: This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions.
Which are the important beans lifecycle methods?
https://siddharthnawani.blogspot.com/2019/10/spring-bean-life-cycle.html
How can you inject a Java Collection in Spring?
Spring offers the following types of collection configuration elements:
The <list> type is used for injecting a list of values, in the case that duplicates are allowed.
The <set> type is used for wiring a set of values but without any duplicates.
The <map> type is used to inject a collection of name-value pairs where name and value can be of any type.
The <props> type can be used to inject a collection of name-value pairs where the name and value are both Strings.
What is bean auto wiring?
The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for a bean by inspecting the contents of the BeanFactory without using <constructor-arg> and <property> elements.
Explain different modes of auto wiring?
The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection:
no: This is default setting. Explicit bean reference should be used for wiring.
byName: When autowiring byName, the Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.
byType: When autowiring by datatype, the Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exist, a fatal exception is thrown.
constructor: This mode is similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.
autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.
Are there limitations with autowiring?
Limitations of autowiring are:
Overriding: You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring.
Primitive data types: You cannot autowire simple properties such as primitives, Strings, and Classes.
Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.
Difference between Setter Injection and Constructor Injection
https://codenuclear.com/difference-between-setter-injection-and-constructor-injection/
Are Singleton beans thread safe in Spring Framework?
Spring framework does not do anything under the hood concerning the multi-threaded behavior of a singleton bean. It is the developer’s responsibility to deal with concurrency issue and thread safety of the singleton bean.
While practically, most spring beans have no mutable state (e.g. Service and DAO clases), and as such are trivially thread safe. But if your bean has mutable state (e.g. View Model Objects), so you need to ensure thread safety. The most easy and obvious solution for this problem is to change bean scope of mutable beans from “singleton” to “prototype“.
How do you turn on annotation based autowiring?
<beans>
<context:annotation-config />
</beans>
What are the different types of events in spring framework?
Spring’s ApplicationContext provides the functionality to support events and listeners in code. We can create beans that listen for events which are published through our ApplicationContext. Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. So if a bean implements the ApplicationListener, then every time an ApplicationEvent gets published to the ApplicationContext, that bean is notified.
public class AllApplicationEventListener implements ApplicationListener < ApplicationEvent >
{
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent)
{ //process event
}
}
Spring provides the following 5 standard events:
ContextRefreshedEvent : This event is published when the ApplicationContext is either initialized or refreshed. This can also be raised using the refresh() method on the ConfigurableApplicationContext interface.
ContextStartedEvent : This event is published when the ApplicationContext is started using the start() method on the ConfigurableApplicationContext interface. You can poll your database or you can re/start any stopped application after receiving this event.
ContextStoppedEvent : This event is published when the ApplicationContext is stopped using the stop() method on the ConfigurableApplicationContext interface. You can do required house keeping work after receiving this event.
ContextClosedEvent : This event is published when the ApplicationContext is closed using the close() method on the ConfigurableApplicationContext interface. A closed context reaches its end of life; it cannot be refreshed or restarted.
RequestHandledEvent : This is a web-specific event telling all beans that an HTTP request has been serviced.
Apart from above, you can create your own custom events by extending ApplicationEvent class. e.g.
public class CustomApplicationEvent extends ApplicationEvent
{
public CustomApplicationEvent ( Object source, final String msg )
{
super(source);
System.out.println("Created a Custom event");
}
}
To listen this event, create a listener like this:
public class CustomEventListener implements ApplicationListener < CustomApplicationEvent >
{
@Override
public void onApplicationEvent(CustomApplicationEvent applicationEvent) {
//handle event
}
}
And to publish this event, you will need the help of applicationContext instance.
CustomApplicationEvent customEvent = new CustomApplicationEvent( applicationContext, "Test message" );
applicationContext.publishEvent ( customEvent );
Name some of the design patterns used in Spring Framework?
There are loads of different design patterns used, but there are a few obvious ones:
Proxy – used heavily in AOP, and remoting.
Singleton – beans defined in spring config files are singletons by default.
Template method – used extensively to deal with boilerplate repeated code e.g. RestTemplate, JmsTemplate, JpaTemplate.
Front Controller – Spring provides DispatcherServlet to ensure an incoming request gets dispatched to your controllers.
View Helper – Spring has a number of custom JSP tags, and velocity macros, to assist in separating code from presentation in views.
Dependency injection – Center to the whole BeanFactory / ApplicationContext concepts.
Factory pattern – BeanFactory for creating instance of an object.
Are Singleton beans thread safe in Spring Framework?
No Singleton bean in Spring is not Thread Safe. The two concepts are not even related.
Singletons are about creation. This design pattern ensures that only one instance of a class is created at any point of time. Spring just manage the life cycle of singleton bean and maintains single instance of object.
Thread safety is about execution. Eventually thread safety depends on the code and the code only. And this is the reason why Spring beans are not thread safe.
How to get ServletContext and ServletConfig object in a Spring Bean?
There are two ways to get Container specific objects in the spring bean.
Implementing Spring *Aware interfaces, for these ServletContextAware and ServletConfigAware interfaces.
Using @Autowired annotation with bean variable of type ServletContext and ServletConfig. They will work only in servlet container specific environment only through.
@Autowired
ServletContext servletContext;
How IOC container will create Object for Private constructor classes?
Answer: Spring internally will use reflection API and it will modify the constructor Accessibility and it will create the object of private constructor class also , by using reflection only Spring is doing autowiring and setting the objects into another object.
What are all the AOP advices used in Spring Transaction internally?
Answer: In Spring transaction internally two Advices they used. Before starting the operation it will start the transaction and if operation success it will call commit operation . Here Spring transaction used “Around Advice” and When Saving the Data Error came at that time it will call rollback operation here they used “throws Advice”
Difference between @Component & @Bean
@Component auto detects and configures the beans using classpath scanning whereas @Bean explicitly declares a single bean, rather than letting Spring do it automatically.
@Component does not decouple the declaration of the bean from the class definition where as @Bean decouples the declaration of the bean from the class definition.
@Component is a class level annotation where as @Bean is a method level annotation and name of the method serves as the bean name.
@Component need not to be used with the @Configuration annotation where as @Bean annotation has to be used within the class which is annotated with @Configuration.
We cannot create a bean of a class using @Component, if the class is outside spring container whereas we can create a bean of a class using @Bean even if the class is present outside the spring container.
@Component has different specializations like @Controller, @Repository and @Service whereas @Bean has no specializations.
No comments:
Post a Comment