Hello World in Spring

In this lesson of the Spring tutorial, we will create a simple HelloWorld example. To do this, we need to cover at first the topic of the bean in Spring. Beans are just object instances that are managed by Spring. The IoC (Inversion of Control) container, which is one of the core parts of Spring, is responsible for managing the lifecycle of a bean.

1. Spring configuration

To define a bean in Spring you need to use Spring configuration. You have three types of configuration in Spring:

  • Java-based configuration (also known as JavaConfig),
  • Annotation-based configuration,
  • XML-based configuration.

At the beginning of this tutorial, we will focus on Java-based configuration. We do that because it has many advantages over different styles of configuration. One of the benefits is that when you refactor your classes, your IDE will automatically update your JavaConfig.

2. Java-based configuration example

2.1 HelloWorldPrinter class

To our example, we will use the HelloWorldPrinter class that just print “Hello world” String in its print method.

2.2. Configuration class

To create a JavaConfig class, you just create a standard class and annotate it with @Configuration annotation. When annotating a class with this annotation, you say to Spring, that this class contains one or more beans. So let’s create a class named HelloWorldConfiguration and annotate it with @Configuration.

To define a bean inside a Configuration class, you create a method and annotate it with @Bean. A name of the method indicates a bean id, which is used to identify a bean. As you can see inside of this method, we just return a new HelloWorldPrinter object instance.

2.3. HelloWorldExample class

Now we will call the print method of the HelloWorldPrinter class. Let’s create a class named HelloWorldExample.

Inside the main method of this class, at first, we create a context using the AnnotationConfigApplicationContext class. Application context in Spring is responsible for beans creation. AnnotationConfigApplicationContext is one of the implementations of ApplicationContext, which supports, apart from others, beans defined in classes annotated with @Configuration. As you can see, we pass to the constructor of this class our configuration class, HelloWorldConfig.

Next, we’ve used this context to get the bean of type HelloWorldPrinter. As you remember, we defined a method that returns a bean of this type in our configuration class HelloWorldConfig. The last line of the main method calls the print method. And as you may think, the result of running the main method of HelloWorldExample class is:

3. Summary

In this lesson of the Spring tutorial we’ve learned what is a bean in Spring. We’ve found out what are the types of configurations that you can use in Spring. Later I’ve shown you how to define a Spring bean using Java-based configuration. At the end we’ve created an example that loads a Spring configuration class and calls a bean method.

Dependency injection in Java

In this tutorial lesson, we will discuss one of the major concepts of Spring which is dependency injection. Before I explain to you what dependency injection is, let’s have a look on below example.

1. Tightly coupled classes example

Let’s create the class named SlowEngine with the method start. For the sake of this example, let’s make this method just print “Slow engine start” string:

And let’s assume that we have the class Car that uses this SlowEngine class. This class has also the method start that calls the SlowEngine.start() method.

And let’s construct the class CarExample which will just create the Car object and then call its start method.

As you can suppose the result of running the above class is like presented below:

But the class Car is highly dependent on the SlowEngine class because in the constructor of the class Car we create a new instance of the class SlowEngine. What if instead the SlowEngine class we just want to use another class like the FastEngine? Then we need to modify the class Car itself.

To avoid such a situation, we can use dependency injection. I will explain it to you by example.

2. Dependency injection example

2.1. Creating an interface and implementing it

So let’s create the interface Engine with the method start.

Then modify the class SlowEngine to implement the Engine interface, so it looks like this:

And now let’s create another class FastEngine that also implements the Engine interface:

As you can see these two methods differ only by the String they print.

2.2 Using an interface as a constructor parameter

But let’s now focus on dependency injection. As you remember in the first implementation of our Car class, we’ve created a new instance of the SlowEngine class in the constructor. To avoid this fact, we can inject an instance of an appropriate class as a parameter in the constructor. So let’ have a look on below example:

2.3 Testing dependency injection example

Now we can use whatever implementation of the Engine class we want. So let’s have a look at the class below:

As you can see in the method createAndStartCarWithFastEngine we create at first an instance of the SlowEngine class. And then we pass it in a constructor to the Car class. At the end, we call the method start of newly created Car instance. Similarly, we do in the second method. The result of calling the above main method will be:

As you can see in the second example, the Car class is now not dependent on any concrete implementation of the Engine interface. It’s only dependent on the Engine interface itself.

Spring framework has many features thanks to which we can make dependency injection much easier. I will cover this topic in the nest lesson of this tutorial.

Java methods

In Java there is a type of entity called a method. Methods help us in organizing our code. A method consists of a header and a body. Let’s have a look at the example of a method:

1. Method header

1.1. Method modifiers

The first line of a method is a header. It contains important information about a method. The first two words public static are modifiers. We will cover this topic more accurately later in this tutorial. Until I explain what it exactly means, just remember that with every method you create, you should now use these public static modifiers.

1.2. Method return type

The third word you see in this method is the int keyword. When it’s placed in this place, it defines a type of variable returned by a method. So you can return from a method any type you want. And you don’t have to return any type. Then instead of a return type you use the keyword void.

1.3. Method name

The fourth word is add. This word indicates method name. Later we can call this method using this name.

1.4. Method parameters

Next in the method you can see an opening bracket. Inside brackets, we give parameters that are passed into methods. So in general, you can pass variables to the method and you can later operate on them. When you declare parameters that are passed to a method, you have to declare their types and names, which you can later use inside this method. You can pass as many parameters to a method, as you want. Every parameter you separate by comma. You don’t have to pass any parameter to the method. Then after a method name you just put an opening and closing bracket like this: ().

In this example, we passed 2 parameters to our method. The first one is of type int and has the name firstNumber. The second one is also of type int and has the name secondNumber.

2. Method body

2.1. Curly brackets

We put a method body in curly brackets. So as you can see the first line of above code ends with an opening curly brace {. And the last line of this code ends with an ending curly brace }. What’s between them is a method body.

2.2. Code inside method body

Inside a method body, you can place your code. The first line of code inside method body in above code is:

So as you can know from this lesson, we declare here variable of type int named sum. Later we assign to this variable a sum of two numbers: firstNumber and secondNumber.

2.3. Returning value from method

The second line of the method body is:

We use return keyword in Java to return some value. So our method will return the value stored inside variable named sum. Remember about it, that the value you return from a method, needs to have exactly the same type as the return type declared in a method header.

2.4. Returning directly from method

Actually, in the example above, we haven’t had to declare variable sum. So instead of having two lines of code inside body of our method:

We can have had only one:

And our method will work in this case exactly the same. So it will return the sum of firstNumber and secondNumber.

3. How to call method in Java

To call a method in Java you give a method name and after that, you pass parameters inside brackets. Let’s create a new class in Eclipse named MethodCallExample. After creating it, change its content like in the following listing:

In the the first line of the main method we have:

In this line we declare the variable named sumInMain of type int. Then we assign to this variable the value returned by the method named add. To the method add we pass 2 parameters: values 1 and 2.

This cause that our add method is called. The value 1 is assigned to the method parameter firstNumber. And the value 2 is assigned to the variable named secondNumber. In the first line of the add method:

the value of these 2 parameters is added and the value 3 is assigned to the variable sum.

Then in the last line of the method add:

the value 3 is returned from the method add.

After that we come back from the method add to this line in the main method:

And we assign the value returned by the add method, to the variable sumInMain.

After that, we print the content of the variable using System.out.println() method.

So if you run this method, the result will be like this:

Java variables

In this lesson of Java tutorial, we are going to talk about Java variables. Variables are used to store some values. Maybe you remember from your math lessons at school that you used some variables, e.g. x. You assigned some value to it, like:

and you did some operations on these variables. Variables in Java are pretty similar. You can assign a value to a variable in Java and then operate on this variable.

1. Variable declaration

Variables in Java can have many types. One of the types is int, which is an abbreviation from an integer. You can store integer numbers in this variable. To use a variable, you have to at first declare it. To declare a variable in Java, you have to at first write its type and then its value. Let’s have a look on below line of code:

Above line of code is a variable declaration. The first word indicates a type of variable. This variable has type int. Next word indicates a variable name. The name of this variable is “counter”. At the end of the line with a variable declaration, you have to put a semicolon.

So the general format of variable declaration is:

2. Assigning value to variable

After declaring a variable, you can assign a value to it. After doing that, this value will be stored in this variable. To assign a value to a variable, you have to use = sign, like in the line of code below.

In the above line of code, we assign value 1 to a variable counter.

So the general format of variable declaration in Java is:

3. Printing variable value to console

Now, I’m going to print the content of the variable counter to the console. To do this I will use the System.out.println() method. We will pass a variable of type int to this method.

So let’s go to Eclipse and in our project named JavaTutorial create a new class named VariableExample. If you don’t remember how to do that, you can find this information here. After creating this class let’s copy paste code below to your eclipse:

Let’s run this program. The output visible in console is like this:

As you can see the System.out.println() method prints the value stored in the variable named counter. So it doesn’t print just the name of the variable, but the value which is stored in this variable. We can do many things with variables, and they are useful when creating a program, as you will see later in this tutorial.

4. Declaration and assignment of variable in one line

We can also move declaration and assignment of a variable into one line. So we can do in Java something like this:

Which is equal to:

So now you can copy and paste below code to you Eclipse class VariableExample:

And as you can see this program also prints 1 to the console.

Java – Convert String to int – Detailed guide

In most of the cases, the best option to convert String to int in Java is to use the method Integer.parseInt(String):

Let me explain this method below.

Integer.parseInt(String s) method:

The Integer.parseInt(String) method takes a String as a parameter and returns a primitive int value.
If you run the code above, you will get the result like printed below:
The characters of the String passed to this method must be all decimal digits. The only exception is the first character which can be the minus ‘-‘ or the plus ‘+’ character.

 

Integer.parsentInt(String) method signature

You can find below the explanation what kind of parameters the int Integer.parseInt(String string) method takes, what it returns and what exception it can throw.

Parameters Returns Throws
String string int NumberFormatException
The string containing an int to be parsed int value which is the result of parsing The exception which is thrown when the parameter cannot be parsed to int

 

Parsing negative int

Using the Integer.parseInt methods you can parse as well negative values. Look at the example below.

The result of running the above code is:

 

Parsing an int with a plus sign

With the parseInt method, you can parse as well an int with the plus ‘+’ sign at the beginning.

The result of the code above is:

 

 

Parsing not an integer: NumberFormatException

When using the Integer.parseInt(String) you need to pass as a parameter to this method a String which can be parsed to an integer. Let’s try to pass a String as a parameter which is not an integer and see what will be the result.

When you try to run the program you will get the exception:

The exception was thrown because the value 5.1 is not an integer.

 

Parsing a random String: NumberFormatException

You will get a similar error trying to use any other String which is not an integer with the method parseInt. Let’s have a look at the class StringToIntRandomStringParameter:

The result this time is:

 

Page 4 of 4

Privacy Preference Center

Necessary

Advertising

Analytics

Other