Category: Spring

Aspect oriented Programming is a cross cutting concepts to OOP. AOP in Spring is used in replacement to EJB for it’s declarative programming style. in this tutorial we will look into different advices that AspectJ supports in Spring.

First of all an Advice is a functionality that we want to execute before or after some method is getting executed.
There are 4 types of Advices that Spring Supports.

BeforeAdvice : this advice is executed before every method call

AfterAdvice : this advice is executed after every method call. please note that this will not get executed if a method throws some exception

AfterThrowingAdvice : this advice is executed after every method throws some configured exceptions

AroundAdvice : this advice is executed before and after every method call

let us dive directly to code part as the above explanation is straight forward.Step1: Let us look into POM.xml file

now let us start writing the classes that were shown in the above configuration file.Step3: write a class named BeforeAdvice.java which will implement MethodBeforeAdvice.java interface. this interface has before method which gets executed before every method call

That’s it guys we have finished coding advices in spring.practical scenario : this kind of approach is very much useful while writing logging facility in projects.
please test the code on your own, and let me know if anything is needed.

Hello everybody, its a long gap that i have not written a post in my blog. This post could be my last post in 2015. today we are going to see how to integrate Spring’s one of the best feature Spring Boot with Spring data and MongoDB.

Step 4: create the controller class which can handle the request coming from client. in this example the controller is called GlobalController.java. The controller class is autowired with MongoTemplate Object and StudentRepository, so let us create StudentRepository so that it will get injected into the controller, when the class loads to spring container. MongoTemplate is readily configured in the AppConfig.java file.

Hello everybody, this time i took little long time to post an article here. Here i came up with a very powerful integration pack called “Integration of Spring data rest with AngularJS and MongoDB”. Now a days this combination is best suited for SPA – “Single Page Application” with light weight back end support with mongodb. Now we will have a Jump start into the tutorial. this tutorial will assume the prior basic knowledge of

Java8

Spring & Spring Data Rest

MongoDB

the project structure looks as below.

Before proceeding with the Spring integration with angularjs and mongodb, please install mongodb and start the mongodb server. if everything goes well server startup should look as below.

Now install any GUI client for mongodb for easy access, we can even access mongodb with out client but this is for better user experience. I personally use “Robomongo” and once you connect Robomongo to MongoDB server that will look as below.

Once everything is ready and inplace, let us start with writing the code. I have used Maven to manage the dependencies and hence the pom.xml looks as below.

With the above two files we are done with the configuration part. Let us talk about ApplicationConfig.java a little more in deep. At the top of the class please take a close look, i have annotated the class with “@EnableWebMvc”, which will enable all “@Component” based class and scans them when the application is loaded by the web container. The annotation “@EnableWebMvc” is equivalent to “”. Moving little forward “@ComponentScan” will scan all the @Component based classes. Now comes the “@EnableMongoRepositories” which will load all the repositories. Finally we have imported a core class from the Spring API called “RepositoryRestMvcConfiguration” this is the class responsible for converting the domain objects back and forth to JSON format and acts as a communication bridge between clint(browser) & backend. In this class we have innitialised two beans called “MongoDBFactory” & “MongoTemplate” since if we have any operation to do apart from Repository implementation then we can use of “MongoTemplate” object to fulfill that.

Here comes the exact repository that we were talking from little while. Please observe the repository carefully. Its an interface extending one more interface called “MongoRepository”.The goal of Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores.The central interface in Spring Data repository abstraction is Repository (probably not that much of a surprise). It takes the domain class to manage as well as the id type of the domain class as type arguments. This interface acts primarily as a marker interface to capture the types to work with and to help you to discover interfaces that extend this one. The CrudRepository provides sophisticated CRUD functionality for the entity class that is being managed. MongoRepository extends the basic CrudRepository.

Now we done with the java part and now its time for us to write the Html and java script. please download latest AngularJS library and include the “angular.min.js” inside your project, after including please write a file called “mongo.module.js” and out the following content into it.

/**
*
*/
var myApp = angular.module('myApp', ['controllers']);

Now write an AngularJs controller which is responsible for firing the Ajax request to the Spring and get the data in REST format. create a folder called “controllers” and create a file “controllers.js” and put the following content into it.

That is it guys we are done from coding part and its time for us to build the application and deploy it to server.
Once we deploy the application into the server, please install an Add on to firefox or chrome called “RESTClient” from which we can test our repositories are working or not.

Once you fire the request as shown in the above screen shot, we should get the response from the service as below.

Now try to open our page “index.html” and in firebug console we could see the same response as above which means pur angularjs is firing the request and our Spring repositories are responding to the request.

Hello every one, recently in one of my project i had a requirement that i need to generate multiple views based on the request type, this has lead me to write this post. In this article i will be explaining about “ContentNegotiatingViewResolver” class.

ContentNegotiatingViewResolver class is a implementation of ViewResolver. The ContentNegotiatingViewResolver does not resolve the view by itself unlike the ViewResolver based on the request type or the Header type in fact this delegates the request to other ViewResolvers that are configured explicitly.

This view resolver uses the requested media type to select a suitable View for a request. The requested media type is determined through the configured ContentNegotiationManager. Once the requested media type has been determined, this resolver queries each delegate view resolver for a View and determines if the requested media type is compatible with the view’s content type). The most compatible view is returned.

Let us look into the above class little deep, First we have created ContentNegotiationManager which is used to determine the requested media types of a request by delegating to a list of ContentNegotiationStrategy instances. By default PathExtensionContentNegotiationStrategy is consulted (which uses the URL extension e.g. .xls, .pdf,.json..) , followed by ParameterContentNegotiationStrategy (which uses the request parameter ‘format=xls’ e.g.), followed by HeaderContentNegotiationStrategy (which uses HTTP Accept Headers) the ContentNegotiationManager instance is injected by Spring Container.Snippet

From past few days i was working on Apache Solr Technologies to index data in one of my projects. Today i wanted to elaborate on this concept, this post assumes that you already have Apache Solr installed on your system, if not please install the latest( > 4.1) version from here. Read the instruction from solr site make the Solr server up and running. Once this Solr is up and running we can go to Admin dashboard by hitting the following url http://localhost:8983/solr.

Now its time for us to dive into Spring coding inorder to push data to solr server. this project is written on top of Spring4, SpringData, Solr4, Maven and Eclipse Luna.

first lets create a maven project and put the below code in your pom.xml file and the project structure looks as below.

Now its time for to start with the configurations and let me remind since we are using Spring for as the core framework i will make use of Java configuration capability of Spring. so all my configurations are just java codes with out xml files. let us start with database config firstDBConfig.java

The above code is responsible for injecting the database properties and creating the datasource and finally injecting datasource into jdbc template class.
Now let us write the solr configuration integrated to spring.SolrConfiguration.java

Above class is responsible for creating the Solr Server object and injecting that to SolrTemplate class, using which we can perform operation over solr server. now to make our project web compatible lets code WebApplication initializer as below which acts similar to web.xml, this works only with servlet 3.0 container (tomcat7 and above)

Now the code concept of spring solr come here, Spring Data Solr, part of the larger Spring Data family, provides easy configuration and access to Apache Solr Search Server from Spring applications. It offers both low-level and high-level abstractions for interacting with the store.

Derived queries and annotations for Solr specific functionallity allow easy integration into existing applications. So spring data has provided Repositories to deal with different operations of Spring.

Now let us look at the resource files that i used in this project 1.application.properties and 2.log4j.properties
please put the below files in “scr/main/resources” folder of your maven project.application.properties

Note : please find the log file in d drive as i have given in log4j.properties file. please chage the drive location if you need.

Now we have done with the coding part, it is time for deployment, from cmd please navigate to location of project and issue the command as mvn clean install package this should build the project with all the required dependencies and final artifact would be spark-solr.war file.
now deploy this war file in apache tomcat under webapps directory and put the below url in your browser.http://localhost:8080/spark-solr/solr/controller/load

Once we hit the url the controller calls the service layer and from service layer invoke dao layer to ftch the data from database abd returned back to service layer now in service layer we have the object od Solr repository and using that we push the data to solr.

After tha data is pushed we cah check tha data in solr using the solr admin page. as below

using my previous post we can pull the data from solr and show on custom UI.
Happy coding 🙂 happy Solr 🙂

Hi all,These days i am taking little time to post new topics as i am doing little R&D in spring’s latest projects like ‘SpringBoot’ and ‘SpringData’. Now here is the post which will explain about ‘SpringData’. Please follow the code little carefully as i wrote block comments in order to better understand the logic. this project is designed under Maven,Spring4.1.1.RELEASE, Eclipse Luna and Tomcat 8.0.11.

Please find the below is the project structure, First let us start with required dependencies for the project as shown below.pom.xml

Let us carry on with all the configurations required by the project and then with the actual logic. below is the code for the ‘application.properties’ file and ‘applicationContext.xml’application.properties this file is fully loaded with all properties which are required by major databases, just uncomment what ever you need and use it.

Now it is time for us to write Java Configurations for Spring to initialize various bean objects and to recognize various annotations in the project, also let us write a configuration for servlet initialization instead of traditional web.xml

ApplicationConfig.java : this class is responsible for initialising the DataSource,JpaTransactionManager and for setting Hibernate properties

Now let us design our domain objects, data transfer objects and User defined Exceptions. In this case our domain object is “Person.java”. in this class we have a static inner class which is called “Builder”, the responsibility of Builder class is to create Person objects and return them.Person.java

Since all our Domain Objects,DTO objects and custom exception types are in place, its time for us to write our Repository Interface. Spring Data has given an out of the box functionality for CRUD operations called CRUDRepository and there are many other Repositories which will extend from this base interface and one of them is “JpaRepository”. It is prety straight forward to design a repository all you have to do is to create an interface which extends the JpaRepository interface. The JpaRepository interface is a JPA specific extension to the Repository interface and it gives you the access to following methods which are used to implement the CRUD application:

delete(T entity) which deletes the entity given as a parameter.
findAll() which returns a list of entities.
findOne(ID id) which returns the entity using the id given a parameter as a search criteria.
save(T entity) which saves the entity given as a parameter.

Once we have our PersonRepository interface ready to use, let us start with service layer to hadle the business logic.PersonService.java : This interface is responsible for basic operations on the domain object in connection with the underlying database.

The implmentation for the above service interface is as below.Note : all the methods of interface are implemented with default definition and only create has the exact logic, the others are left for you people to implement.Also observer @Transactional annotation it is at the method level not at the class level.
Please observer that the PersonRepository class gets injected by the spring container and CRUD operation capability is provided by it.PersonServiceImpl.java

Now every thing is completed from logic point of view let us start with the controller class class to handle different request from client.Please observe that i have hard coded the values from domain object here, in my next post i will be making this as dynamic, for time being this is for testing.

Hi guys, here is my 80th blog post which talks about calling Restful service using Spring’s “RestTemplate”. This codebase is executed under Spring 3.1 and 4.0 dependencies. The project structure looks as shown below.

let me explain one scenario here, the calling REST service can return JSON Object or an XML Document back to consumer. it si up to the implementation how to convert JSON back to Java Object or convert Xml Back to Java.
We have many Marshallers and UnMarshallers available some of them are Jaxb2Marshaller,Jibx Marshaller, XStreamMarshaller,XmlBeanMarshaller..etc, i personally used Jaxb2Marshaller in this project. let us now dive into the code, there is no much explanation needed in the code, please follow the comments over the code blocks.