Monday, April 27, 2015

Spring Interview Questions

What is the difference between Inversion of Control and Dependency Injection ?
Inversion of Control is a design in which the framework (or reusable library) calls the implementations provided by the application rather than having the application call the methods in a framework to carry out generic tasks. Here the control flow of a program is inverted, were the framework takes control of the program flow instead of the programmer. Hence the component can perform its task entirely by itself when all the necessary information or functionality is provided by application implementation. IoC allows to decouple the application into separate independent components. Such decoupling of components enables easier testing in isolation, reduced complexity and better maintenance by switching components.

One of the most common versions of IoC is Dependency Injection, where necessary object instances (functionality) are passed into an object through constructors, setters or service look-ups in order for the object to function independently. Each component must declare a list of dependencies required to perform it's task. At runtime a special component, generally an IoC Container performs binding between these components. It tries to provide values for published component dependencies.
           In other words we do not create our objects but describe how they should be created. We don’t directly connect our components and services together in code but describe which services are needed by which components in a configuration file. A IOC container is responsible for hooking it all up.

What are different types of Dependency Injections ?
There are three types of dependency injection
  • Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters.
  • Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
  • Interface Injection (e.g. Avalon): Injection is done through an interface.
Spring supports only Constructor and Setter Injection.

What is a Spring autowiring ?
Autowiring enables Spring to inject dependencies without having to specify those explicitly. Spring inspects bean factory contents and establishes relationships amongst collaborating beans. The Spring container can autowire relationships between collaborating beans without using <constructor-arg> and <property> elements. The autowire attribute of the <bean/> element specifies the autowire mode for a bean definition. Below are autowiring modes which instruct Spring container to use autowiring for dependency injection.

Spring Autowiring Modes
Mode Description
no It is default setting which means no autowiring.
byName Autowiring by property name. Spring container matches the properties of the beans on which autowire attribute is set to byName in XML config with the beans defined by the same names in the configuration file.
byType Autowiring by property datatype of the property. Spring container matches the properties of the beans on which autowire attribute is set to byType in the XML config with the type which matches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown.
constructor 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.

Autowiring can be specified in bean classes also using @Autowired annotation. To use @Autowired annotation in bean classes, we must first enable the annotation in spring application using <context:annotation-config /> configuration. The @Autowired annotation can then be used to autowire bean on the setter method, constructor, a property or methods with arbitrary names and/or multiple arguments. By default, the @Autowired annotation implies the dependency is required similar to @Required annotation, however, you can turn off the default behavior by using (required=false) option with @Autowired. Simple properties such as primitives, Strings, and Classes though cannot be autowired.

What are various Bean scopes in Spring ? Which is the default Bean scope ?
By default, all Spring beans are singletons. The prototype scope is used to create a new bean instance each time.

Spring Bean Scopes
Scope Description
singleton Scopes the bean definition to a single instance per Spring container (default).
prototype Allows a bean to be instantiated any number of times (once per use).
request Scopes a bean definition to an HTTP request. Only valid when used with a webcapable Spring context (such as with Spring MVC).
session Scopes a bean definition to an HTTP session. Only valid when used with a webcapable Spring context (such as with Spring MVC).
global-session Scopes a bean definition to a global HTTP session. Only valid when used in a portlet context.

Does Singleton bean from Spring Container is thread safe ?
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. Also all the spring scopes are enforced during the creation of the spring bean.

Describe Spring Bean Life Cycle ?
A Spring Bean represents a POJO component performing some useful operation. All Spring Beans reside within a Spring Container also known as IOC Container. The Spring Framework is transparent and thereby hides most of the complex infrastructure and the communication that happens between the Spring Container and the Spring Beans. This section lists the sequence of activities that will take place between the time of Bean Instantiation and hand over of the Bean reference to the Client Application.
  1. The Bean Container finds the definition of the Spring Bean in the Configuration file.
  2. The Bean Container creates an instance of the Bean using Java Reflection API.
  3. If any properties are mentioned, then they are also applied. If the property itself is a Bean, then it is resolved and set.
  4. If the Bean class implements the BeanNameAware interface, then the setBeanName() method will be called by passing the name of the Bean.
  5. If the Bean class implements the BeanClassLoaderAware interface, then the method setBeanClassLoader() method will be called by passing an instance of the ClassLoader object that loaded this bean.
  6. If the Bean class implements the BeanFactoryAware interface, then the method setBeanFactory() will be called by passing an instance of BeanFactory object.
  7. If there are any BeanPostProcessors object associated with the BeanFactory that loaded the Bean, then the method postProcessBeforeInitialization() will be called even before the properties for the Bean are set.
  8. If the Bean class implements the InitializingBean interface, then the method afterPropertiesSet() will be called once all the Bean properties defined in the Configuration file are set.
  9. If the <bean> definition in the configuration file contains a init-method attribute, then the value for the attribute will be resolved to a method name in the Bean class and that method will be called immediately upon instantiation.
  10. The postProcessAfterInitialization() method will be called if there are any Bean Post Processors attached for the Bean Factory object.
  11. If the Bean class implements the DisposableBean interface, then the method destroy() will be called when the Application no longer needs the bean reference.
  12. If the <bean> definition in the configuration file contains a destroy-method attribute, then the corresponding method definition in the Bean class will be called just before the bean is removed from the container.
@PostConstruct and @PreDestroy annotations are not exclusive to Spring, but they are a standard and consequently widely used in many container managed environments inclusing spring. @PostConstruct annotation defines a method that will be called after a bean as been fully initialized. In other words it will be called after bean construction and all dependency injection. @PreDestroy annotation defines a method that will be called just before a bean is destroyed, which is usually useful for resource clean up.

 


How to inject collections using spring ? How to inject collections using annotations ?
Spring offers four types of collection configuration elements to inject Java Collection types List, Set, Map, and Properties which are as follows:

Element Description
<list> It helps in wiring ie injecting a list of values, allowing duplicates.
<set> It helps in wiring a set of values but without any duplicates.
<map> It is used to inject a collection of name-value pairs where name and value can be of any type.
<props> It is used to inject a collection of name-value pairs where the name and value are both Strings.

Either <list> or <set> can be used to wire any implementation of java.util.Collection or an array.

How are properties configured in Spring ?
The PropertyPlaceholderConfigurer class is used to access the properties from properties file into bean configuration using a special variable format ${variable}.
   <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="location">
            <value>database.properties</value>
      </property>
   </bean>
@Configuration
@PropertySource("classpath:root/test.props")
public class SampleConfig {

 @Value("${test.prop}")
 private String attr;
 
 @Bean
 public SampleService sampleService() {
  return new SampleService(attr);
 }

 @Bean
 public PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
  return new PropertySourcesPlaceholderConfigurer();
 }
}

What is a Validator and How to use it ?
Something.

What is the difference between @Autowire and @Inject ?
@Inject: It is part of javax.inject package. The inject annotation can be used on fields, constructors and setter methods. It is used for dependency injection when the bean instance is instantiated by the container.

@Autowired: It is the part of Spring's org.springframework.bean.factory package. It used for dependency injection using on fields, constructors and setter methods.

@Resource: It is part of javax.annotation package. It can be used on fields or setter methods. The @Resource annotation takes a 'name' attribute which will be interpreted as the bean name to be injected, thus following by-name autowiring semantics.

@Qualifier: It is also the part of JSR 330's javax.inject package and also part of Spring's org.springframework.beans.factory package. It is used to wire the bean based on the property name when more than one bean of the same type exists in the container.

What is Aspect Oriented Programming ?
Aspect oriented programming provides modularity using aspects and by cross-cutting concerns. A cross-cutting concern is a concern that should be centralized in one location in code as possible, such as transaction management, authentication, logging, security etc. AOP recommends to abstract and encapsulate crosscutting concerns.
  The Concern is behavior expected to have in a module of an application and is defined as a functionality to implement.The cross-cutting concern is a concern which is applicable throughout the application and it affects the entire application.

Jointpoint: It defines were we want to execute the code. A joinpoint is a point in the execution of the application where an aspect can be plugged in. Such point could be a method being called, an exception being thrown, or even a field being modified. These are the points where the aspect’s code can be inserted into the normal flow of the application to add a new behavior. Spring supports only method execution join point.

Advice: Advice defines both the what and the when of an aspect. Advice represents an action taken by an aspect at a particular join point.  There are different types of advices depending upon the position they are called in a program, such as before, after or around:

Before Advice: It executes before a join point. It does not have the ability to interrupt the execution flow proceeding at the joint point unless it throws an exception
After Returning Advice: it executes after a joint point completes normally.
After Throwing Advice: it executes if method exits by throwing an exception.
After (finally) Advice: it executes after a join point regardless of join point exit whether normally or exceptional return.
Around Advice: It executes before and after a join point.

Pointcut: It is a collection of joint points. Pointcuts help to narrow down the joinpoints advised by an aspect. A pointcut definition matches one or more joinpoints at which advice should be woven. It is an expression language of AOP that matches join points.
Pointcuts are specified using explicit class and method names or through regular expressions that define matching class and method name patterns. Spring supports union, and intersection operation on pointcuts. Union means the method that either pointcut matches, while Intersection means the method that both pointcuts match.

Aspect: An aspect is a class which contains advices and pointcuts.
<bean id="minstrel“ class="com. knight.Minstrel"/>
<aop:config>
   <aop:aspect ref="minstrel">
      <aop:pointcut id="questPointcut" expression="executing  embarkOnQuest() " />
      <aop:before method="singBefore“ pointcut-ref="questPointcut“ arg-names="bean" />
      <aop:after-returning method="singAfter“ pointcut-ref="questPointcut“ arg-names="bean" />
   </aop:aspect>
</aop:config> 
 
The AspectJ annotations can be integrated with Spring AOP framework to allow easy method interception. AOP proxy is an object created by the AOP framework in order to implement the aspect contracts such as advise method executions. Once spring AOP is enable it automatically generate a proxy for the bean on which to intercept method invocations and ensure that corresponding advice gets executed as needed. @AspectJ Support is enabled using Java and XML configuration as below:
<aop:aspectj-autoproxy/>
@Configuration
@EnableAspectJAutoProxy
public class AppConfig {
}

Common AspectJ annotations are as below:
@Before – Run before the method execution
@After – Run after the method returned a result
@AfterReturning – Run after the method returned a result, intercept the returned result as well.
@AfterThrowing – Run after the method throws an exception
@Around – Run around the method execution, combine all three advices above.

@Aspect
public class LoggingAspect {
 
   @AfterReturning(
      pointcut = "execution(* com.sample.customer.Customer.addCustomer(..))",
      returning= "result")
   public void logAfterReturning(JoinPoint joinPoint, Object result) {

      System.out.println("Method Name : " + joinPoint.getSignature().getName());
      System.out.println("Method Return Value : " + result);
   }
 
}
....
public class Customer {

  public String addCustomer(){
      // Add customer business logic
      return "customer";
  }
}


What is weaving ? What are the different points where weaving can be applied ?
Weaving is the process of linking aspects with other application types or objects to create an advised object. Weaving can be done at compile time, at load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.

What is dependency checking ?
The Spring IoC container has the ability to check for the existence of unresolved dependencies of a bean inside the container. This feature ensures that all properties (or all properties of a certain type) are set on a bean. In many cases though the bean has default values for the properties, or some properties do not apply to all usage scenarios, limiting the usage of this feature. Dependency checking can be enabled or disabled on per bean basis. By default dependency checking is disabled. Dependency checking can be handled in several different modes as below.

none – No dependency checking. Hence bean properties which have no value specified are simply not set.
simple – Dependency checking is performed for primitive types and collections (map, list)..
objects – Dependency checking is performed for properties of object type i.e. collaborators.
all – Dependency checking is done for properties of any type i.e. collaborators, primitive types and collections.

In XML-based configuration the 'dependency-check' attribute is specified in the bean definition.
 <bean id="CustomerBean" class="com.entity.Customer" 
         dependency-check="simple">
 
  <property name="person" ref="PersonBean" />
  <property name="action" value="buy" />
 </bean>

@Required Annotation: In most scenarios we need to check that a particular property has been set instead of all the properties of certain types (primitive, collection or object). The @Required Annotation is used to enforce such checking, which makes sure that annotated property has been set. In order to apply the @Required annotation the RequiredAnnotationBeanPostProcessor must be enabled using "<context:annotation-config />" in the bean configuration file. The Required annotation is more flexible than dependency checking in XML file, because it can apply to a particular property only.

Which settings are inherited by a child bean from its parent bean ?
In Spring, the inheritance is supported in bean configuration for a bean to share common values, properties or configurations. A child bean can inherit its parent bean configurations, properties and some attributes. A child bean definition will inherit constructor argument values, property values and method overrides from the parent, with the option to add new values. If init method, destroy method and/or static factory method are specified, they will override the corresponding parent settings. The remaining settings will always be taken from the child definition: depends on, autowire mode, dependency check, singleton, lazy init.

Which is the central IoC container interface in Spring IoC ?
The org.springframework.beans.factory.BeanFactory is the actual representation of the Spring IoC container that is responsible for containing and otherwise managing the beans. The BeanFactory interface is the central IoC container interface in Spring. Its responsibilities include instantiating or sourcing application objects, configuring such objects, and assembling the dependencies between these objects.

Difference between BeanFactory and ApplicationContext ?
ApplicationContext interface is derived from the BeanFactory interface and hence includes all functionality of the BeanFactory such Bean instantiation and wiring. It also provides some of the other features as below and hence is recommended over BeanFactory:
  • Automatic BeanPostProcessor registration
  • Automatic BeanFactoryPostProcessor registration
  • Convenient MessageSource access and thus provides internationalization support (i18n)
  • ApplicationEvent publication

How do you make a bean to lazy load in ApplicationContext which loads all beans eagerly during startup ?
A bean is loaded only when an instance of that Java class is requested by any other method or a class. BeanFactory (and subclasses) container loads beans lazily. ApplicationContext container follows a pre-loading methodology, were all beans are instantiated as soon as the spring configuration is loaded by a container. The "default-lazy-init" attribute of the beans element tells the application context if its needs to lazily load the beans. The default value of the attribute is false which makes the ApplicationContext non lazily load the beans.
<beans default-lazy-init="true">
        <!-- all your beans -->
</beans>

What are interceptors available in Spring MVC ?
Spring provides interceptors in order to intercept the HTTP Request and carry out processing before handing it over to the controller handler methods. The Spring interceptors implement the HandlerInterceptor interface or by override abstract class HandlerInterceptorAdapter that provides the base implementation of this interface. HandlerInterceptor declares three methods based on where we want to intercept the HTTP request.
  • The preHandle method is used to intercept the request before it’s handed over to the handler method. It returns true when wants to process the request through another interceptor or to send it to handler method if there are no further interceptors, else returns false when no further processing is needed. 
  • The postHandle method is called when HandlerAdapter has invoked the handler but DispatcherServlet is yet to render the view. This method can be used to add additional attribute to the ModelAndView object to be used in the view pages.
  • The afterCompletion is a callback method that is called once the handler is executed and view is rendered.

Describe the life cycle of Spring MVC Request ?

Spring defines a single front controller known as the DispatcherServlet which handles all the requests to the web application. The DispatcherServlet is declared in the web.xml and all the requests to be handled by DispatcherServlet are mapped using the corresponding URL mapping. The DispatcherServlet’s job is to send the request on to a Spring MVC controller, were an application may have several controllers. The DispatcherServlet consults one or more handler mappings which determine appropriate controller based on the request URL. Handler mappings typically map a specific controller bean to a URL pattern, and implement the HandlerMapping interface along with the Ordered interface to indicate the precedence. DispatcherServlet then sends the request on to its chosen controller.
        At the controller, the request’s payload is dropped off and the information is processed. The controller logic comes up with the result after processing the model. The controller then packages up the model data and the name of a view for display into a ModelAndView object. The ModelAndView object contains model data and the logical name to be used to lookup for actual html/jsp view. The controller sends the request and the ModelAndView object back to the DispatcherServlet.
        The DispatcherServlet asks a View Resolver to help find the actual JSP View. The view resolver uses the logical view name in the ModelAndView object returned from a controller to look up a View bean to render results to the user. A view resolver is any bean that implements the ViewResolver interface. The DispatcherServlet  then delivers the model data to the View implementation thus completing the request’s job. The view also has access to the request variables added in the ModelMap which contains information about the model, inside the ModelAndView container.

The @Controller annotation indicates that a particular class serves the role of a controller without implementing Controller interface. Spring does not require you to extend any controller base class or reference the Servlet API. @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.




Why Spring MVC is better than Struts2 ?
  • Spring MVC is loosely coupled framework whereas Struts is tightly coupled.
  • Spring provides a very clean division between controllers, JavaBean models, and views.
  • In Struts 2 Actions are newly instantiated every time a request is made, whereas in Spring MVC the default behavior is to act as a Singleton. Spring MVC Controllers are created once and held in memory/shared across all requests.
  • Spring’s MVC is very flexible. Unlike Struts, which forces the Action and Form objects into concrete inheritance (thus they cannot inherit from any other class), Spring MVC is entirely based on interfaces. Furthermore, just about every part of the Spring MVC framework is configurable via plugging in custom interface. Convenience classes are also provided by spring as an implementation option.
  • Spring MVC is truly view-agnostic. We can use JSP else can use any other view technologies including Velocity and XLST. Also custom view mechanism can also be used by implementing the Spring View interface for integration.
  • Struts provides very specific tags which allow the request parameters to bind with Action Form fields and show binding/validation errors. Spring MVC, on other end has one simple bind tag that handles everything, making the JSP pages smaller and have more pure HTML content.
  • Spring Controllers are configured via IoC like any other objects. This makes them easy to test, and beautifully integrated with other objects managed by Spring.
  • Spring MVC web tiers are typically easier to test than Struts web tiers, due to the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.
  • Using Spring MVC, the web tier becomes a thin layer on top of a business object layer. Struts on the other hand leave us on our own in implementing our business objects. Spring provides an integrated framework for all tiers of the application.
  • Unlike Struts, Spring MVC have no ActionForms and it binds directly to domain objects.
  • Spring MVC code is more testable since validation has no dependency on Servlet API.
  • Struts imposes dependencies on application Controllers since they must extend a Struts class. Spring MVC on the other hand doesn’t force this, although there are convenience Controller implementations that can be choosen to extend.
  • Spring offers better integration with view technologies other than JSP (Velocity / XSLT / FreeMarker / XL etc.)

What is Spring Web Flow ? How does it work ?
Spring web flow is an extension to Spring MVC, which provides the ability to define an application’s flow external to the application’s logic and create reusable flows that can be used across multiple applications.
           The FlowController is a Spring MVC controller which acts as a front controller for Spring Web Flow applications. It is responsible for handling all requests pertaining to a flow. The flowExecutor property is the only mandatory property wired with a flow executor, which ultimately carries out the steps described in the flow. The Flow Executor keeps track of all of the flows that are currently being executed and directs each flow to the state they should go next. A mapping URL is used to interact with the Spring Web Flow and is configured to the FlowController using handler mappings such as SimpleUrlHandlerMapping. The flow registry is effectively a librarian that curates a collection of flow definitions. The flow executor asks the flow registry for the flow when it needs a flow.
          There are three main elements that make up an application flow: states, events, and transitions. States are points in a flow where some activity takes place e.g. Action, Decision, Start, End, Subflow and View. View and Action states represents the user's and application’s side of conversation respectively. Once a state has completed, it fires an event, which is simply a String value indicating the outcome of the state. The event fired by a state should be mapped to a transition to serve any purpose. Transitions defines the actual flow unlike the state which defines an activity within a flow. They indicate which state the flow should go to next.

What is WebApplicationContext ?
The WebApplicationContext is an extension of the plain ApplicationContext and has some extra features such resolving themes, determining associated servlet necessary for web applications.

What is JdbcTemplate in Spring ? What is benefit of using JdbcTemplate ?
The JdbcTemplate class is the central class in the JDBC core package. It simplifies the use of JDBC since it handles the creation and release of resources. This helps to avoid common errors such as forgetting to always close the connection. It executes the core JDBC workflow like statement creation and execution, leaving application code to provide SQL and extract results. This class executes SQL queries, update statements or stored procedure calls, imitating iteration over ResultSets, convert database data into primitives or objects and extraction of returned parameter values. It also catches JDBC exceptions and translates them to the generic, more informative, exception hierarchy defined in the org.springframework.dao package.

What types of transaction management does Spring support ?
There are two types of transaction management supported by Spring, as below:

Programmatic transaction management: It allows to manage the transaction with the help of programming in your source code. That gives you extreme flexibility, but it is difficult to maintain.
       To implement programmatic approach we need an instance of TransactionDefinition with the appropriate transaction attributes. The DefaultTransactionDefinition can be used which has default transaction attributes. The transaction can be started by calling getTransaction() method on PlatformTransactionManager and passing the reference of TransactionDefinition, which returns an instance of TransactionStatus. The TransactionStatus objects helps in tracking the current status of the transaction. If everything goes fine then we can use commit() method of PlatformTransactionManager to commit the transaction, otherwise we use rollback() to rollback the complete operation.
      TransactionDefinition def = new DefaultTransactionDefinition();
      TransactionStatus status = transactionManager.getTransaction(def);

      try {
         String sqlInsertQuery = "insert into Student (name, age) values (?, ?)";
         jdbcTemplateObject.update(sqlInsertQuery, name, age);

         // Get the latest student id to be used in Marks table
         String sqlGetIdQuery = "select max(id) from Student";
         int sid = jdbcTemplateObject.queryForInt( sqlGetIdQuery );

         sqlInsertQuery = "insert into Marks(sid, marks, year) values (?, ?, ?)";
         jdbcTemplateObject.update( sqlInsertQuery, sid, marks, year);

         System.out.println("Created Name = " + name + ", Age = " + age);
         transactionManager.commit(status);
      } catch (DataAccessException e) {
         System.out.println("Error in creating record, rolling back");
         transactionManager.rollback(status);
         throw e;
      }

Declarative transaction management: Declarative transaction management approach allows to manage the transaction with the help of configuration instead of hard coding it in the source code. It separates the transaction management from the business code and uses only annotations or XML configuration to manage the transactions. Below are the steps associated with declarative transaction:
  • We use <tx:advice /> tag, which creates a transaction-handling advice and same time we define a pointcut that matches all methods we wish to make transactional and reference the transactional advice.
  • If a method name has been included in the transactional configuration then created advice will begin the transaction before calling the method.
  • Target method will be executed in a try-catch block.
  • If the method finishes normally, the AOP advice commits the transaction successfully otherwise it performs a rollback.
   <tx:advice id="txAdvice"  transaction-manager="transactionManager">
      <tx:attributes>
      <tx:method name="create"/>
      </tx:attributes>
   </tx:advice>
 
   <aop:config>
      <aop:pointcut id="createOperation" expression="execution(* com.abc.StudentJDBCTemplate.create(..))"/>
      <aop:advisor advice-ref="txAdvice" pointcut-ref="createOperation"/>
   </aop:config>
 
   <!-- Initialization for TransactionManager -->
   <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource"  ref="dataSource" />    
   </bean>

What is Spring Integration ?
Spring intergration is framework build upon core spring and provides integration solutions for event-driven and messaging-centric architectures.It provides a layered architecture and interface-based contracts between layers. The messaging system follows the pipes-and-filters model. The "filters" represent any component that is capable of producing and/or consuming messages, and the "pipes" transport the messages between filters so that the components themselves remain loosely-coupled. A Message is a generic wrapper which consists of a payload and headers.

How did you configure caching using spring ?
Spring 3.1 provides support for transparently adding caching into an existing Spring application, thus allowing consistent use of various caching solutions. Spring provides two Java annotations for the caching declaration: @Cacheable and @CacheEvict, which allow methods to trigger cache population or cache eviction. The cache:annotation-driven element is defined for xml configuration in the application context. The @Cacheable annotation is used in front of methods that are cacheable – that is, methods for whom the result is stored into the cache so on subsequent invocations (with the same arguments), the value in the cache is returned without having to actually execute the method. If only the value of the cache is specified in the @Cacheable annotation in front of the method, then the default key generation or the one specified as default will kick in. The developer can also use SpEL to pick the arguments of interest, perform operations or even invoke arbitrary methods to specify the custom key generation using the key attribute. The @CacheEvict annotation marks the methods that perform cache eviction, that is methods that act as triggers for removing data from the cache. @CacheEvict requires one to specify one (or multiple) caches that are affected by the action, allows a key or a condition to be specified but in addition, features an extra parameter allEntries which indicates whether a cache-wide eviction needs to be performed rather then just an entry one (based on the key).
<!-- CacheManager manages and controls all the Cache -->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
 <property name="cacheManager" ref="ehcache"/>
</bean>
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
 <property name="configLocation" value="classpath:config/ehcache.xml"/>
 <property name="shared" value="true"/>
</bean>

<!-- Configuration in ehcache.xml -->
<ehcache xsi:noNamespaceSchemaLocation="ehcache.xsd" 
   updateCheck="true" 
   monitoring="autodetect" 
   dynamicConfig="true"
   maxBytesLocalHeap="150M">
   
 <diskStore path="java.io.tmpdir"/> 
 
 <cache name="searchResults"
       maxBytesLocalHeap="100M"
       eternal="false"
       timeToIdleSeconds="300"
       overflowToDisk="true"
       maxElementsOnDisk="1000"       
       memoryStoreEvictionPolicy="LRU"/>       
 
 <cache name="podcasts"
       maxBytesLocalHeap="40M"
       eternal="false"
       timeToIdleSeconds="300"
       overflowToDisk="true"
       maxEntriesLocalDisk="1000"
       diskPersistent="false"
       diskExpiryThreadIntervalSeconds="120"
       memoryStoreEvictionPolicy="LRU"/>         
 
 <cache name="referenceData"
       maxBytesLocalHeap="5M"
       eternal="true"
       memoryStoreEvictionPolicy="LRU">
       <pinning store="localMemory"/>
  </cache>
</ehcache>
 



No comments:

Post a Comment