Annotations in Java

Why annotation is required, we can use comment also to give information about data like metadata ?

  • If you use comment in class, field, constructor or method level then it can reach max to max source file only, means when compiler compile .java file to .class file. It exclude comment section so it won’t be available.
  • Before Java 5 to achieve such kind of functionality used xml based configuration like in hibernate needs a .hbm file or for servlet needs to add configuration in web.xml file.

What is Annotation in java ?

  • In the Java computer programming language, an annotation is a form of syntactic metadata (a set of data that describes and gives information about other data) that can be added to Java source code.
  • Classes, methods, variables, parameters and packages may be annotated. Unlike Javadoc tags, Java annotations can be reflective in that they can be embedded in class files generated by the compiler and may be retained by the Java VM to be made retrievable at run-time. It is possible to create meta-annotations out of the existing ones in Java.
  • Annotations are the part of java from Java 5 before that there is not concept like annotations. So we should use xml based configuration.

Type of Annotations

  • Marker Annotation – @Override, @WebListener
  • Single Valued Annotation – @SuppressedWarning(“unchecked”) or @SuppressedWarning(value = “unchecked”)
  • Multi valued Annotation – @WebServlet(name = “login”, urlPatterns = “/login”)

Why are Annotations better then xml ?

XML – Servlet configuration in web.xml before Servlet 2.X like below code

<web-app>
     <servlet>
        <servlet-name>helloworld</servlet-name>
        <servlet-class>HelloWorld</servlet-class>
     </servlet>
     <servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>/helloworld</url-pattern>
     </servlet-mapping>
</web-app>

Annotation – after Servlet 3.X

 @WebServlet(name = “helloworld“, urlPatterns = “/helloworld”)

See the difference so before java 5, need to write a code in xml file.

Ex – Servlet – like above, Hibernate – domain.hbm.xml, Spring – Need to create bean in applicatonContext xml file

XML v/s Annotation

XML Annotation
up to jdk1.4 jdk 5.0
JDBC 3.X JDBC 4.0
Servlet 2.5 Servlet 3.X
Struts 1.X Struts 2.X
JSF 1.X JSF 2.X
Hibernate 3.2.4 Hibernate 3.2.5
Spring 2.X Spring 3.X
EJB 2.X EJB 3.X

General purpose annotations

  • @Override – annotation informs the compiler that the element is meant to override an element declared in a superclass. Overriding methods will be discussed in Interfaces and Inheritance. While it is not required to use this annotation when overriding a method, it helps to prevent errors.
  • @SuppressWarnings – annotation is used to suppress compiler warnings for the annotated element. Specifically, the unchecked category allows suppression of compiler warnings generated as a result of unchecked type casts.
  • @Deprecated – Starting with J2SE 5.0, you deprecate a class, method, or field by using the @Deprecated annotation. Additionally, you can use the @deprecated Javadoc tag tell developers what to use instead. Using the annotation causes the Java compiler to generate warnings when the deprecated class, method, or field is used.
  • @FunctionalInterface – An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification. Conceptually, a functional interface has exactly one abstract method.

Meta annotations

  • @Documented – to ensure that classes using your annotation show this in their generated JavaDoc also.
  • @Inherited – It means that subclasses of annotated classes are considered having the same annotation as their superclass.
  • @Target – it defined that where you can put your annotation based on type like class, method, constructor, field, localvariable.
  • @Retention – based on Retention Policy can use that like Source, Class or at Runtime.

For more detail, Please watch below video –

How to execute cron job in Spring ?

Spring framework has built-in support for scheduled tasks. So can schedule tasks using XML as well as annotation also.

XML

<task:scheduled-tasks>
     <task:scheduled ref="beanName" method="methodName" cron="*/5 * * * * *"/>
</task:scheduled-tasks>

Annotation – An annotation that marks a method to be scheduled. Exactly one of the cron(), fixedDelay(), or fixedRate() attributes must be specified.

Processing of @Scheduled annotations is performed by registering a ScheduledAnnotationBeanPostProcessor. This can be done manually or, more conveniently, through the <task:annotation-driven/> element or @EnableScheduling annotation.

@Scheduled(cron=“0/10 * * * * *”) //execute after every 10 seconds

For more detail, Please watch below video –

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

What is Spring data JPA ?

  • The too much boilerplate code has to be written to execute simple queries as well as perform pagination, and auditing.
  • It aims to significantly improve the implementation of data access layers by reducing the effort to the amount that’s actually needed.
  • As a developer, you write your repository interfaces, including custom finder methods, and Spring will provide the implementation automatically.
  • We can remove some boilerplate code by creating an abstract base repository class that provides CRUD operations for our entities. This means that we can create concrete repositories by extending that base repository class.
  • It has a lot of customization points, including items like query auto-generation by convention, query hints, and auditing.

Features

  • Sophisticated support to build repositories based on Spring and JPA
  • Support for Querydsl predicates and thus type-safe JPA queries
  • Transparent auditing of domain class
  • Pagination support, dynamic query execution, ability to integrate custom data access code
  • Validation of @Query annotated queries at bootstrap time
  • Support for XML based entity mapping
  • JavaConfig based repository configuration by introducing @EnableJpaRepositories.

Advantages

  • Don’t need to write persisting, updating, deleting or searching logic.
  • Reduce a lot of basic DB code.
  • No need to create implementation classes to perform basic CRUD operations.
  • Just extends Repository class and it takes the domain class to manage as well as the id type of domain class as type arguments in Interface.
  • The interface acts as a marker interface to capture the type of work and to help you to discover interfaces that extend this one.

Types of Repositories

public interface Repository public interface CRUDRepository
public interface PagingAndSortingRepository
public interface JpaRepository

For more detail, Please watch below video –

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

 

What is Entity Manager in Hibernate ?

  • Hibernate Entity Manager implements the programming interfaces and lifecycle rules as defined by the JPA 2.0 specification.
  • Together with Hibernate Annotations, this wrapper implements a complete (and standalone) JPA persistence solution on top of the mature Hibernate Core.
  • The Entity Manager API is used to access a database in a particular unit of work. This interface is similar to the Session in Hibernate.
  • It is used to create and remove persistent entity instances, to find entities by their primary key identity, and to query over all entities.
<!– Need to use below dependency in pom.xml file to integrate entity manager -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>5.2.5.Final</version>
</dependency>

What is Entity Manager Factory?

  • An entity manager factory provides entity manager instances, all instances are configured to connect to the same database, to use the same default settings as defined by the particular implementation, etc.
  • Interface used to interact with the entity manager factory for the persistence unit. When the application has finished using the entity manager factory, and/or at application shutdown, the application should close the entity manager factory.
  • You can prepare several entity manager factories to access several data stores. This interface is similar to the Session Factory in native Hibernate.

What is Local Container Entity Manager Factory Bean? 

  • FactoryBean that creates a JPA EntityManagerFactory according to JPA’s standard container bootstrap contract.
  • This is the most powerful way to set up a shared JPA EntityManagerFactory in a Spring application context.
  • The EntityManagerFactory can then be passed to JPA-based DAOs via dependency injection.
  • Note that switching to a JNDI lookup or to a LocalEntityManagerFactoryBean definition is just a matter of configuration.

What is Persistence context?

  • The scope of this context can either be the transaction, or an extended unit of work.
  • Entities are managed by javax.persistence.EntityManager instance using persistence context.
  • Each EntityManager instance is associated with a persistence context.
  • Within the persistence context, the entity instances and their lifecycle are managed.
  • Persistence context defines a scope under which particular entity instances are created, persisted, and removed.
  • A persistence context is like a cache which contains a set of persistent entities, So once the transaction is finished, all persistent objects are detached from the EntityManager’s persistence context and are no longer managed.

What is HibernateJpaVendorAdapter?

  • JpaVendorAdapter implementation for Hibernate EntityManager.
  • Its kind of one property of EntityManager and contains some configuration like generate DDL, show SQL, format SQL etc.
<!-- Entity Manager Factory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" p:dataSource-ref="dataSource" p:packagesToScan="com.mightyjava.model">
   <property name="jpaVendorAdapter">
       <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" p:showSql="true" p:generateDdl="true"/>
   </property>
</bean>  

What is JpaTransactionManager?

  • This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access.
  • JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction.
  • This transaction manager also supports direct DataSource access within a transaction.
<!-- Transaction -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" p:entityManagerFactory-ref="entityManagerFactory" />

For more detail, Please watch below video –

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

What is “p” namespace ?

  • Spring’s “p” name space is an alternative to using the property tag.
  • Using “p” namespace, we can perform dependency injection by directly using the attribute of bean tag instead of using the property.
  • “p” namespace is more compact than property tag.
  • Using “p” namespace reduces the amount of XML required in Spring configuration.
  • The size of spring configuration using p namespace is typically less than one with using property tag.
xmlns:p="http://www.springframework.org/schema/p"

For more detail, Please watch below video –

 

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

What is Hibernate ?

  • It is an object-relational mapping(ORM) framework for the Java language.
  • It provides a framework for mapping an object-oriented domain model to a relational database.
  • It solves object-relational impedance mismatch problems by replacing direct, persistent database accesses with high-level object handling functions.
  • Its primary feature is mapping from Java classes to database tables, and mapping from Java data types to SQL data types.
  • It also provides data query and retrieval facilities. It generates SQL calls and relieves the developer from manual handling and object conversion of the result set.

What is Session Factory?

  • SessionFactory is an interface and extends Referenceable, Serializable and which is available in “org.hibernate” package.
  • Creates Sessions, Usually, an application has a single SessionFactory and it is long live multithreaded object so can say it’s a thread safe.
  • Usually, one session factory should be created for one database so if have multiple databases then multiple session factories required.
  • SessionFactorys are immutable. The behavior of a SessionFactory is controlled by properties supplied at configuration time. These properties are defined on Environment.
Configuration config = new Configuration();
config.configure(“hibernate.cfg.xml”);
SessionFactory sessionFactory = config.buildSessionFactory();

What is Session?

  • A Session is used to get a physical connection with a database.
  • The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.
  • The session is not Thread Safe.
  • Sessions are opened by a SessionFactory and then are closed when all work is complete.
  • A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions.
SessionFactory sessionFactory = config.builedSessionFactory();
Session session = sessionFactory.getCurrentSession();

What is Data source?

  • Spring obtains a connection to the database through a DataSource.
  • A DataSource is part of the JDBC specification and is a generalized connection factory.
  • It allows a container or a framework to hide connection pooling and transaction management issues from the application code.
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="url" value=“jdbc:mysql://localhost:3306/db_name" />
    <property name="driverClassName" value=“com.mysql.jdbc.Driver" />
    <property name="username" value=“root" />
    <property name="password" value=“root" />
</bean>

For more detail, Please watch below video –

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

What is mvc:annotation-driven?

  • Spring 3 introduces an MVC XML configuration namespace that simplifies the setup of Spring MVC inside your web application.
  • If you don’t include mvc:annotation-driven also your MVC application would work if you have used the context:component-scan for creating the beans or defined the beans in your XML file.
  • mvc:annotation-driven does some extra job on configuring the special beans that would not have been configured if you are not using this element in your XML file.
  • This tag would register the HandlerMapping and HandlerAdapter required to dispatch requests to your @Controllers.

For more detail, Please watch below video –

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

What is Aspect Oriented Programming ?

  • Aspect Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect.
  • AOP entails breaking down program logic into distinct parts called so-called concerns. The functions that span multiple points of an application are called cross-cutting concerns and these cross-cutting concerns are conceptually separate from the application’s business logic.

Scenario where we should use AOP –

  • Logging
  • Auditing
  • Declarative Transactions
  • Security
  • Caching

AOP Concepts

  • Aspect: a modularization of a concern that cuts across multiple classes. Transaction management is a good example of a crosscutting concern in enterprise Java applications. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (the @AspectJ style).
  • JoinPoint: a point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.
  • Advice: action taken by an aspect at a particular join point. Different types of advice include “around,” “before” and “after” advice. Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors around the join point.
  • Pointcut: a predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut expression language by default.

For more detail, Please watch below video –

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

What is a context in Java ?

  • A context can be said as the running environment that is provided to the current unit of work. It may be the environment variables, instance variables, state of the classes, and so on.
  • Like ServletContext represents the servlet’s environment within its container, Similar to ApplicationContext, which represents the Spring application’s core environment within the Spring container.
  • There are Servlet’s ServletContext, JSF’s FacesContext, Spring’s ApplicationContext, JNDI’s InitialContext, and all these contexts follow the Facade Pattern to Abstract the environment specific details to the end user, providing the interface methods to Interact with.

Spring Context Configuration

In Spring web applications, there are two contexts that get initialized at server startup, each of which is configured and initialized differently.

1.Application Context

2.Web Application Context

What is Application Context?

  • ApplicationContext defines the beans that are shared among all the servlets.
  • In ApplicationContext, Spring loads applicationContext.xml file and creates the context for the whole application using ContextLoaderListener that we define in our application’s web.xml.
  • applicationContext.xml is the root context configuration for every web application There will be only one application context per web application.
  • If you are not explicitly declaring the context configuration file name in web.xml using the contextConfigLocation param, Spring will search for the applicationContext.xml under WEB-INF folder and throw FileNotFoundException, if it could not find this file.
  • Beans that defines your business logic, database interaction and other stuff that has to be shared across servlets should reside in applicationContext.xml.

This is the part of web.xml file

<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/root-context.xml</param-value>
</context-param>

In the above configuration, we are asking Spring to load root-context.xml and create an Application Context from it.

If contextConfigLocation is not mentioned as in the above snippet, It will by default look for

/WEB-INF/applicationContext.xml

At server startup, ContextLoaderListener instantiates all bean defined in applicationcontext.xml assuming you have defined the following in context XML file :

<import resource="test1.xml" />
<import resource="test2.xml" />
<import resource="test3.xml" />
<import resource="test4.xml" />

The beans are instantiated from all four configuration files test1.xml, test2.xml, test3.xml, test4.xml

What is WebApplicationContext?

  • There can be multiple WebApplicationContext in a single web application.
  • It is another servlet specific context that is loaded based on the dispatcher servlets configured in the application’s web.xml file.
  • Each dispatcher servlet has its own servlet-context initialized from <servlet-name>-servlet.xml file.
  • This allows us to categorize the incoming requests based on the servlet’s URL-pattern and handle them accordingly, such that one of the dispatcher servlets could help serving the web pages via Controller, while another one could be used to implement a stateless REST web service.
  • We understand that a single web application can have multiple dispatcher-servlet configurations.
  • dispatcher-servlet.xml defines the beans that are related only to that servlet. Beans that deals with servlet requests/web requests like controllers, message converters, interceptors should reside in dispatcher-servlet XML.

If we want to change the name of the dispatcher-servlet file name or change its location, we can add init-param with contextConfigLocation as param-name, as can be seen below

<servlet>
  <servlet-name>spring</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring-servlet.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
   <servlet-name>spring</servlet-name>
   <url-pattern>/</url-pattern>
</servlet-mapping>

So with spring-servlet init-param specified as in the above web.xml code snippet, Spring no more finds the dispatcher-servlet context file with the name spring-servlet.xml, but instead looks for the one specified as the init-param value for contextConfigLocation, i.e. spring-servlet.xml.

Object creations workflow

  • When tomcat starts, beans defined in dispatcher-servlet.xml are instantiated.
  • DispatcherServlet extends FrameworkServlet. In FrameworkServlet bean instantiation takes place for the dispatcher. In our case dispatcher is FrameworkServlet.
  • The beans are all instantiated from all four test1.xml, test2.xml, test3.xml, test4.xml. After the completion of bean instantiation defined in applicationcontext.xml then beans defined in dispatcher-servlet.xml are instantiated.
  • Instantiation order is root is application context, then FrameworkServlet.

Difference between the two contexts

  • ApplicationContext is the root-context that has bean configurations we might want to use (and re-use) across the entire application as singletons.
  • There can be multiple WebApplicationContexts for each of the dispatcher servlets we specify in our application’s web.xml.
  • WebApplicationContext internally extends ApplicationContext, and as a child inherits all the beans from its parent. So we can also override the parent bean within our WebApplicationContext.
  • It’s always better to keep a clear separation between middle-tier services such as business logic components and data access classes (which we prefer defining in the ApplicationContext XML), and web-related components such as controllers and view-resolvers (which we prefer defining in the respective dispatcher-servlet‘s WebApplicationContext).
  • Configuring contextLoaderListener is completely optional. We can boot up a Spring application with just the dispatcher-servlet, without even configuring contextLoaderListener (that loads up the root-context).

For more detail, Please watch below video –

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

 

What is load-on-startup in web.xml file ?

  • The <load-on-startup> is a tag element which appear inside <servlet> tag in web.xml.
  • This tag specifies that the servlet should be loaded automatically on the startup of the web application.
  • The <load-on-startup> value is a positive integer or 0 which specifies the servlets loaded order as per your business logic or what suits your application.
  • When the servlet is loaded by the container, its init() method is called.
  • If <load-on-startup> is the negative integer or the element is not presented then servlets will be loaded when the container decides it needs to be loaded.
<load-on-startup>1</load-on-startup>

For more detail, Please watch below video –

 

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java