Spring boot and Spring MVC Explained

Spring Boot and Spring MVC are not comparable or mutually exclusive. If you want to do web application development using Spring, you would use Spring MVC anyway.

Spring MVC is a sub-project of the Spring Framework, targeting design and development of applications that use the MVC (Model-View-Controller) pattern. Spring MVC is designed to integrate fully and completely with the Spring Framework and transitively, most other sub-projects.

Spring Boot is supposedly opinionated, i.e. it heavily advocates a certain style of rapid development, but it is designed well enough to accommodate exceptions to the rule if you will. In short, it is a convention over configuration methodology that is willing to understand your need to break convention when warranted.

Spring MVC

  1. It is a HTTP oriented web application development framework and is one of the spring modules.
  2. Spring mvc enables a decoupled way of developing web applications. The web application can be implemented in accordance with model view controller design pattern.
  3. It is equivalent to Java Server Faces in the JavaEE stack. Classes annotated with @controller are the most popular elements.
  4. For implementation of Rest based APIs, it has an equivalent @RestController.

Spring Boot :

  1. Create of Quick Application so that, instead of manage single big web application we divide them individually into different Microservices which have their own scope & capability.
  2. Auto Configuration using Web Jar: In normal Spring there is a lot of configuration like DispatcherServlet, Component Scan, View Resolver, Web Jar, XML. (For example, if I would like to configure data source, Entity Manager Transaction Manager Factory). Configure automatically when it’s not available using class-path.
  3. Comes with Default Spring Starters, which come with some default Spring configuration dependency (like Spring Core, Web-MVC, Jackson, Tomcat, Validation, Data Binding, Logging). Don’t worry about versioning issue as well.

Related blog:

Java collection tutorials

Things to remember while learning Java

When you talk about Object Oriented Programming, the best and the most apt example that comes to the mind is Java. Developed by Sun Microsystems, Java leads the way in terms of cross platform programming language and developing application software. The reason Java has gained such a large fan base and unprecedented popularity is because the language deploys a very easy and efficient approach to perform various programming tasks and aid the developers.

 

Its simplicity can sometimes be a distraction and the highly experienced Java developers have always aimed a notch higher and have tried to explore the different possibilities that the language offers. Being a good Java developer is always within touching distance of any computer programming enthusiast, however; it is standing amongst the very bests that matters. 

Below are some tips that might help you grow as a Java developer and gain more knowledge about the language. 

1. Get the basics right

As Java offers so many features and options to the developers, people are sometimes lured into learning too many things in too little time. As a result of this, they get ‘bits and pieces’ knowledge of a few options that Java offers, but their basics hang on a loose thread. Trust me when I say this, Java is one programming language which is easy if you have paid attention to the simple basics, however; it can be frustrating if you get greedy and try to take the shorter route forward.

2. Don’t just read 

Well, if your sole purpose of learning Java is to clear the exam you have the next day, go ahead and mug up all the things that you can and you might just get the passing marks. However; if you are really serious about learning Java and getting better at it, the best way to do it is not by reading, but by implementing. Gain knowledge and then execute what you have learnt, in the form of code. You can never learn Java if you are not willing to get your hands dirty.

3. Understand your code and algorithm

Even if you are writing a simple code having a ‘if else’ statement, as a beginner, start by realizing the code on a piece of paper. The algorithm and the whole compiler process will look so meaningful once you understand the idea behind the code. Even for experts, the best way to solve a complex problem or to formulate an algorithm to solve a Java program is to break the problem into sub-parts and then try to devise a solution for each sub part. When you start getting the solutions right, you will get the confidence to work more.

4. Do not forget to allocate memory 

This tip is particularly useful for those who switch from C, C++ to Java. The memory allocation in Java using the ‘new’ keyword is a necessity as Java is a dynamic programming language. C, C++ does not explicitly have this feature, therefore you must take care while handling array and object declaration in Java. Not using the ‘new’ keyword will show a null pointer exception in the code.

Eg:

1
int array = new int [5];

Note the difference in array declaration in Java and C or C++.

5. Avoid creating useless objects

When you create an object in Java, you use up memory and processor speed from the system. Since object creation is incomplete without allocating memory to it, it is better to keep the object requirements under check and not create unwanted objects in the code.

Eg:

1
2
3
4
5
6
7
8
public class vehicles {
    public List getvehicles(){
        if(null == vehicles){ // this ensures that the object is initialised only when its required
            countries = new ArrayList();
        }
        return vehicles;
    }
}

6. Interface is better than Abstract class

There is no multiple inheritance in Java, and this will be spoon fed to you so many times while learning the language that you will probably never forget it for the rest of your life. However; the tip here in not to remember that there is no multiple inheritance in Java, but the fact that interface will come in handy if you want to implement something like multiple inheritance without using the extends keyword. Remember, in Java, when nothing goes your way, you will always have interface by your side. Abstract class does not always give programmers the liberty of having a variety of methods to work with, however; interface only have abstract methods therefore is does the job of abstract classes and has other advantages as well. 

7. Standard library is a bliss

The biggest advantage that Java has over its predecessors, from a programming point of view, is probably its rich set of standard library methods.  Using Java’s standard library makes the job of a programmer easy, more efficient and gives a well organised flow to the code. Further, operations can be performed easily on the methods specified in the library. 

 

Related blog:

 

Spring boot tutorials

Lazyloading in angular 8 framework

We all know lazy loading is one of the most useful concepts of Angular Routing, and for those of us who have been working with Angular, we know how it brings down the size of large files. This is done by lazily loading the files that are required occasionally.

To start with lazy loading by asynchronously loading the feature module for routing whenever required, we go to the route configuration and use the property loadChildren. Let us see what this property does.

    {path: ‘user’, loadChildren: ‘./users/user.module#UserModule’}

This property loadChildren is used for lazily loading the routes and is not related to child routes or such.

Let us break down what the property’s value means. The loadChildren property accepts a string value which contains the route to the feature module followed by a hash symbol and then the name of the feature module.

Now when the route gets activated, this loadChildren property will get activated and load the requested module. It will then load the requested component and display that component’s template.

Once we have configured this property, we go to the console to see which files are generated.

We will see an extra bundle file generated.
Now if you go to the network tab in the console to see the files generated on routing to the UserModule, you will see one extra file created with some numeric value which might look something like this:

This is how lazy loading gets implemented using the loadChildren feature in the route configuration for the specific feature module. And this creates another bundle file only when that route is navigated to and the data is requested.

This is how we have been working with lazy loading till now, right?

But…
If we look at the route config again,

  {path: ‘user’, loadChildren: ‘./users/user.module#UserModule’}

the loadChildren property accepts a string which means that even if there is a wrong module name or a typo while writing the code, Angular would not know there is something wrong and accept whatever is there as a string until we try building it.

So, let us say we write the config as :

   {path: ‘user’, loadChildren: ‘./users/user.module#UserModulee’},

with an extra ‘e’, it will not throw any error considering it a part of the string.

Therefore,
Angular 8 comes up with support for dynamic imports in our router configuration. This means that we use the import statement for lazy loading the module and this will be understood by the IDEs, webpack, etc.

So when you update to Angular 8, this will automatically accommodate the changes in your application.

Now if you look at how lazy loading is done in this new route config, you will see:

 {path: ‘user’, loadChildren: () => import(‘./users/user.module’).then(m => m.UserModule)};

Now your editor, let’s say VSCode understands what is this syntax and will recognize if there is some mistake and we won't have to wait till build time to realize about an error.

This new syntax now means that loadChildren is a function which will execute when it tries to access the user module. This will asynchronously load the import statement and implement the module.

Related blog:

Hibernate interview questions and answers

Why choose spring boot for the java web applications

Spring Boot just takes away all these pains and let you write the code which matters i.e. application code. All of the Spring Boot features which I mentioned e.g. auto-configuration, Starter POMs or Starter dependency and Spring Boot CLI aims to simplify Java development with Spring.

Spring Boot Initializer

Spring Initializer is another feature of Spring Boot which solves the problem with respect to project structure. It's a web application which allows you to generate a Maven or Gradle project with Java, Kotlin or Groovy and Spring Boot.

All you need to specify is to provide Project MetaData in GUI e.g. name of your project, Group, Artifact etc. It also allows you to choose a starter dependency from a big list e.g. web, JPA, or security starter.

The Spring Initializer project can be accessed at https://start.spring.io/. Once you create a project you can download the Zip file and then open into an IDE like Eclipse or IntelliJ IDEA as explained in Spring Boot Essential course by Nelson Djalo. You can then edit this sample project to put your code.

As per my experience, one of the common problem many Java and Spring developers faces is to start a project. Many of them are clueless about whether to put your Java file, resource file etc.

Though Maven, Gradle, IntelliJ IDEA, and Eclipse help you to give basic structure you still need to proficient on those two skills to get a head start and if you are not familiar with Maven or your IDE, it can be a nightmare.

Spring Boot Initaizer solves this problem and makes it easy to create a Spring-based Java application without really knowing about a lot of internal details of Spring framework.

That's all about some of the essential features of Spring Boot which Java developers should know. These features really make working with Java and Spring fun and productive and that's why more and more companies are adopting Spring Boot for Java development.

Java developers with Spring Boot experience is also in good demand and if you are looking for your next job as Java web developer then Spring Boot skills can really make a difference.


Actuator

The actuator is another awesome feature of Spring Boot which allows seeing what's going on inside a running Spring Boot application. With all its goodness of auto-configuration, there comes a risk of not knowing what is inside your application and that risk is addressed by Spring Actuator.

It provides a lot of insights and metrics about a running application in production. For example, by using Actuator you can find out exactly which beans are configured in the Application context, what are auto-configuration decisions made, what environment variables, system properties, command line arguments are available to an application and many more.

You can even get a trace of HTTP requests handled by the application, along with various useful application metrics e.g. CPU and Memory usage, garbage collection details, web requests, and data source usage.

Spring Boot Actuator also provides several endpoints to retrieve this data e.g. you can get all this using RESTful APIs or you can use its remote shell feature to securely go inside the application and get all this information by issuing commands.

It also exposes all this functionality using JMX MBeans which means you can control them at runtime using a JMX client like JConsole.

At the same time, you also need to secure access to Actuator endpoints because it not only expose confidential information but also it's dangerous. For example, anyone can stop your application by using /shutdown endpoints.

Though, you don't need to worry. Like any other Spring application, you can use Spring Security to protect Actuator endpoints.



Related blog:

 

Java hashset example programs

Java for a developer with small business

I have had a taste of every major programming language under the sun, including functional. But frankly, the ecosystems for most other modern languages/platforms are often very poor and just exhausting, and I'm looking to turn to something stable and still active, so I'm currently re-evaluating Java, which I have had experience with but nothing server-side/web-based. Ruby (particularly, Rails) is still active and productive, but both the quality of information and size of the community seem to be declining in the past 5ish years.

Microsoft has given me little confidence to follow their lead any more with the .NET (Core) platform. Then again, I've had a lot of problems with Java as a language and while streams and lambdas are a welcome addition, the changes around Java lately have been a little WTF as well from an outsider's perspective and I'm concerned about that as well (Oracle's licensing change for their JVM distributions, the JavaEE ownership transfer, the Java trademark thing I *think* causing the Jakarta rename, IBM buying RedHat to me is a wildcard too as with any acquisition).

My client is a small business and I'll be building a web app for them. Very low concurrent users, but data will be in gigabytes. Server-side rendered MVC is plenty fine and probably preferable (with a little JS). Lots of CRUD operations. Multitenancy may come up. There's no requirement for an API, and in fact a website monolith would probably be easier / more productive. I plan to integrate with AWS S3 at a minimum and hope to host on a low-fuss platform like Beanstalk.

A free runtime environment or app server like Tomcat is a must. Comprehensive documentation is a must. And some basic, but solid web security is a must. And there must be decent productivity from the beginning - I'm not above a configuration file, but I can't spend a week to a month just doing boilerplate, which I often hear complaints about with Spring MVC. To reiterate, I'm plenty familiar with Java as a language, particularly pre-1.8, but I've never really touched a servlet.

So those are my constraints, which don't seem to be often discussed here. I've played around with Spring Boot a little bit which seems nice out of the box, until I realized the login mechanism the starter project it generates is worthless (1 ephemeral username + password), and taking the seed project and trying to add database authentication with hashed passwords has been surprisingly difficult. The Spring security docs have like 1 paragraph on this and refer you to insufficient examples, despite the density of the documentation overall.

 

Particularly, trying to seed the app with initial users that pass them through the same bcrypt hasher has left me at a loss (it would be dubious to try to do this with a sql seed file given it requires whitebox knowledge of the password encoder). But then I realized this is probably not a common enterprise scenario when you have stuff like LDAP and SPAs doing JWTs.

 

This brings me back to the nagging feeling that the Java ecosystem is still really made for big teams in big organizations, doing microservices and high scalability and message queues and reactivity etc., and may a poor fit for a project like this. Yet it seems to check so many other boxes. So I'd appreciate any input as to how Java, whether it's JavaEE, Spring, some other framework, etc. are a good fit for me and this project, or any frank suggestions that Java is not worth my time for this given that my skills are not *already* much invested in this ecosystem.

 

Related blog:

java collection tutorials

What are the features Angular 8 features

Angular 8 Updates And Summary of New Features is today’s topic. Angular 8 arrives with an impressive list of changes and improvements including the much-anticipated Ivy compiler as an opt-in feature.

CLI workflow improvements

The CLI is continuing to improve, and now the ng buildng test and ng run are equipped to be extended by 3rd-party libraries and tool. For example, AngularFire already makes use of these new capabilities with a deploy command.

 Web workers

JavaScript is single threaded by definition. Because of this, it is common for more critical tasks like data calls to take place asynchronously. This doesn’t help with elaborate calculations. Those especially are becoming more and more common with an extensive JavaScript solutions, which is why we support the almost all browser web workers by now. They are the scripts that a browser runs in an own thread. Communication with a thread in the browser tab takes place via sending messages.

While web workers have nothing to do with Angular per se, they must be taken into consideration in the build. The goal is to provide one bundle for every web worker. The new Angular CLI accomplishes this task.

 W eb workers allow you to run the CPU intensive computations in the background thread, freeing the main thread to update the user interface.

If you find your application becomes unresponsive while processing data, using Web Workers can help.

 To outsource such a calculation to a background, we must first create the web worker using the Angular CLI.

ng generate worker n-queens

Dynamic imports for lazy routes

Lazy-loaded routes now use the standard dynamic import syntax instead of a custom string. This means that TypeScript and linters will be better able to complain when modules are missing or misspelled.

So a lazy-loaded import that looked like this.

{ path: '/student', loadChildren: './student/student.module#StudentModule' }

Will now look like this.

{ path: `/student`, loadChildren: () => import(`./student/student.module`).then(s => s.StudentModule) }

The change in syntax will be taken care of for you if you’re using the ng upgrade command to upgrade your app. Differential loading

Your Angular 8 apps will now be automagically more performant, thanks to differential loading.

With differential loading, two bundles are created when building for production: a bundle for modern browsers that support ES2015+ and a bundle for older browsers that only support the ES5 version of JavaScript. The correct bundle will be loaded automatically by the browser, thanks to the support of ES6 modules in newer browsers.

This new feature results in the most significant single performance improvement for Angular v8. More modern browsers will be able to load less code and load a much smaller amount of polyfills.

Finally, Angular 8 Updates And Summary of New Features article is over.

 

Related blog:

Spring boot restful webservices crud example

 

Features of hibernate framework for your application

Hibernate supports Inheritance, Associations, Collections

In hibernate if we save the derived class object, then its base class object will also be stored into the database, it means hibernate supporting inheritance

Hibernate supports relationships like One-To-Many,One-To-One, Many-To-Many-to-Many, Many-To-One

This will also supports collections like List,Set,Map (Only new collections)

In jdbc all exceptions are checked exceptions, so we must write code in try, catch and throws, but in hibernate we only have Un-checked exceptions, so no need to write try, catch, or no need to write throws. Actually in hibernate we have the translator which converts checked to Un-checked 😉

Hibernate has capability to generate primary keys automatically while we are storing the records into database

Hibernate has its own query language, i.e hibernate query language which is database independent

So if we change the database, then also our application will works as HQL is database independent

HQL contains database independent commands

While we are inserting any record, if we don’t have any particular table in the database, JDBC will rises an error like “View not exist”, and throws exception, but in case of hibernate, if it not found any table in the database this will create the table for us.

Hibernate supports caching mechanism by this, the number of round trips between an application and the database will be reduced, by using this caching technique an application performance will be increased automatically.

Hibernate supports annotations, apart from XML

Hibernate provided Dialect classes, so we no need to write sql queries in hibernate, instead we use the methods provided by that API.

Getting pagination in hibernate is quite simple.

 

Related blog:

Spring mvc interview questions