Category Archives: Java

Java Collections for Beginners

Java Collections for Beginners

Java Collections are objects that can include many other objects. And these objects can be treated as one set of data.

Collection interfaces (and their most popular implementations)

– List (ArrayList, LinkedList)

– Queue (PriorityQueue):      Deque (ArrayDeque)

– Set (HashSet):     SortedSet              NavigableSet

Let’s look at using List interface (and its ArrayList and LinkedList implementations) that is the most popular.

We could write the code in this way:

package com.linaittech;

import java.util.*;

public class Kolekcje {

public static void main(String args[]) {

List list = new ArrayList();

list.add(“Ela”);
list.add(“Ula”);
list.add(“Ola”);
list.add(“Iza”);
list.add(“Mika”);

System.out.println(list);
System.out.println(“2: ” + list.get(4));
System.out.println(“0: ” + list.get(0));
System.out.println(“1: ” + list.get(1));

LinkedList queue = new LinkedList();

queue.addFirst(“Benek”);
queue.addFirst(“Olek”);
queue.addFirst(“Bolek”);
queue.addFirst(“Tolek”);
queue.addFirst(“Gienek”);
queue.addFirst(“Gienek”);

System.out.println(queue);

queue.removeLast();
queue.removeLast();

System.out.println(queue);

queue.removeFirst();
queue.removeFirst();

System.out.println(queue);

}

}

We have the output:

[Ela, Ula, Ola, Iza, Mika]
2: Mika
0: Ela
1: Ula
[Gienek, Gienek, Tolek, Bolek, Olek, Benek]
[Gienek, Gienek, Tolek, Bolek]
[Tolek, Bolek]

But it’s a bad way. We should write in this way:

package com.linaittech;

import java.util.*;

public class Kolekcje {

public static void main(String args[]) {

List<String> list = new ArrayList<String>();

list.add(“Ela”);
list.add(“Ula”);
list.add(“Ola”);
list.add(“Iza”);
list.add(“Mika”);
list.add(“Wiki”);

System.out.println(list);
System.out.println(“2: ” + list.get(4));
System.out.println(“0: ” + list.get(0));
System.out.println(“1: ” + list.get(1));

LinkedList<String> queue = new LinkedList<String>();

queue.addFirst(“Benek”);
queue.addFirst(“Olek”);
queue.addFirst(“Bolek”);
queue.addFirst(“Tolek”);
queue.addFirst(“Gienek”);
queue.addFirst(“Gienek”);

System.out.println(queue);

queue.removeLast();
queue.removeLast();

System.out.println(queue);

queue.removeFirst();
queue.removeFirst();

System.out.println(queue);

}

}

We have the output:

[Ela, Ula, Ola, Iza, Mika, Wiki]
2: Mika
0: Ela
1: Ula
[Gienek, Gienek, Tolek, Bolek, Olek, Benek]
[Gienek, Gienek, Tolek, Bolek]
[Tolek, Bolek]

The output is the same, so what’s the problem? Because there can some problems with implementing some interfaces using the first example, you should use the second method, in which we see some generics. We use simply generic types here. Compare

List list = new ArrayList();

and

List<String> list = new ArrayList<String>();

The difference is that we know that we will deal with String type. References to generic types should be parametrized. It’s a safer way for us. We can also use Integer, for example.

package com.linaittech;  
 
import java.util.*;  
 
public class Kolekcje {  
 
    public static void main(String[] args) {  
        List <Integer> firstList = new ArrayList<Integer>();  
        List <Integer> secondList = new ArrayList<Integer>();
        
        firstList.add(1);  
        firstList.add(2);  
        firstList.add(3);  
        firstList.add(4);  
        firstList.add(5);  
      
          
        secondList.add(10);  
        secondList.add(20);  
        secondList.add(30);  
        secondList.add(40);  
        secondList.add(50);  
          
        System.out.println(“Our First List-“+ FirstList);  
        System.out.println(“Our Second List-“+ SecondList);
        
        Collections.copy(SecondList, FirstList );
        
        System.out.println(“Our First List After Having Copied-“+ FirstList);
        System.out.println(“Our Second List After Having Copied-“+ SecondList);
        
        Collections.shuffle(FirstList);
        Collections.shuffle(SecondList);
        
        System.out.println(“Our First List After Having Copied-“+ FirstList);
        System.out.println(“Our Second List After Having Copied-“+ SecondList);
    }  
}

Now, we have

List <Integer> FirstList = new ArrayList<Integer>(); 

and

List <Integer> SecondList = new ArrayList<Integer>();

Thanks to generics we know we will deal with Integer type. We can’t add a type that isn’t Integer, for example String. Thanks to that, we can use all methods that are in the Integer class,  and there won’t any complaints during compilation (in Eclipse IDE, for example).

Spring Application with Dependency Injection – Setter (Inner Beans)

Spring Application with Dependency Injection – Setter (Inner Beans)

Let’s see how to write a simple Spring application with DI using constructor. This time we are going to use inner beans. We have the following files in our project:

MainApp.java

package com.linaittech;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”);

Mirek mireczek = (Mirek) context.getBean(“mirek”);
mireczek.mirekMethod();

}

}

Mirek.java

package com.linaittech;

public class Mirek {

private Murek mureczek;
private Burek bureczek;

   public void setMureczek(Murek mureczek) {
System.out.println(“We are inside the setMureczek.” );
this.mureczek = mureczek;
}

 public void setBureczek(Burek bureczek){
System.out.println(“We are inside the setBureczek.” );
 this.bureczek = bureczek;
}

public Murek getMureczek() {
return mureczek;
}

public Burek getBureczek(){
return bureczek;
}

public void mirekMethod() {
mureczek.murekMethod();
bureczek.burekMethod();
}

}

Murek.java

package com.linaittech;

public class Murek {

public Murek(){
System.out.println(“We are inside the Murek constructor.” );
}

public void murekMethod() {
System.out.println(“We are inside the murekMethod.” );
}

}

Burek.java

package com.linaittech;

public class Burek {

public Burek(){
System.out.println(“We are inside the Burek constructor.” );
}

public void burekMethod() {
System.out.println(“We are inside the burekMethod.” );
}

}

Beans.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<beans xmlns=”http://www.springframework.org/schema/beans&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”&gt;

<!– definitions with using inner beans –>
 
<bean id=”mirek”>

<property name=”mureczek”>
<bean id=”murek”/>
</property>

<property name=”bureczek”>
<bean id=”burek”/>
</property>

</bean>

</beans>

You can run it and see the output:

gru 12, 2013 3:10:32 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@44a541: startup date [Thu Dec 12 15:10:32 CET 2013]; root of context hierarchy
gru 12, 2013 3:10:32 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Beans.xml]
gru 12, 2013 3:10:33 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@91762: defining beans [mirek]; root of factory hierarchy
We are inside the Murek constructor.
We are inside the Burek constructor.
We are inside the setMureczek.
We are inside the setBureczek.
We are inside the murekMethod.
We are inside the burekMethod.

The red lines is the most important for us. We injected two methods (murekMethod and burekMethod) from two beans (Murek and Burek) into the Mirek bean. We used the setters in the Mirek bean, and all was managed by Beans.xml. However, here we have beans defined in another bean that is between <property> and </property> elements.

Spring Application with Dependency Injection – Setter

Spring Application with Dependency Injection – Setter

Let’s see how to write a simple Spring application with DI using constructor. We have the following files in our project:

MainApp.java

package com.linaittech;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”);

Mirek mireczek = (Mirek) context.getBean(“mirek”);
mireczek.mirekMethod();

}

}

Mirek.java

package com.linaittech;

public class Mirek {
    
    private Murek mureczek;
    private Burek bureczek;
    
    public void setMureczek(Murek mureczek) {
        System.out.println(“We are inside the setMureczek.” );
        this.mureczek = mureczek;
    }
    
    public void setBureczek(Burek bureczek){
        System.out.println(“We are inside the setBureczek.” );
        this.bureczek = bureczek;
    }
    
    public Murek getMureczek() {
        return mureczek;
    }
    
    public Burek getBureczek(){
        return bureczek;
    }
    
    public void mirekMethod() {
        mureczek.murekMethod();
        bureczek.burekMethod();
    }

}

Murek.java

package com.linaittech;

public class Murek {
    
    public Murek(){
        System.out.println(“We are inside the Murek constructor.” );
        }
    
    public void murekMethod() {
        System.out.println(“We are inside the murekMethod.” );
        }

}

Burek.java

package com.linaittech;

public class Burek {
    
    public Burek(){
        System.out.println(“We are inside the Burek constructor.” );
        }
    
    public void burekMethod() {
        System.out.println(“We are inside the burekMethod.” );
        }

}

Beans.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<beans xmlns=”http://www.springframework.org/schema/beans&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”&gt;

<!– mirek bean definition –>

<bean id=”mirek”>
<property name=”mureczek” ref=”murek”/>
<property name=”bureczek” ref=”burek”/>
</bean>

<!– murek bean definition –>

<bean id=”murek”>
</bean>

<!– burek bean definition –>

<bean id=”burek”>
</bean>

</beans>

You can run it and see the output:

gru 11, 2013 2:36:39 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1f1bf46: startup date [Wed Dec 11 14:36:39 CET 2013]; root of context hierarchy
gru 11, 2013 2:36:39 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Beans.xml]
gru 11, 2013 2:36:39 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1203fe5: defining beans [mirek,murek,burek]; root of factory hierarchy
We are inside the Murek constructor.
We are inside the Burek constructor.
We are inside the setMureczek.
We are inside the setBureczek.
We are inside the murekMethod.
We are inside the burekMethod.

The red lines is the most important for us. We injected two methods (murekMethod and burekMethod) from two beans (Murek and Burek) into the Mirek bean. We used the setters in the Mirek bean, and all was managed by Beans.xml.

Spring Application with Dependency Injection – Constructor

Spring Application with Dependency Injection – Constructor

Let’s see how to write a simple Spring application with DI using constructor. We have the following files in our project:

MainApp.java

package com.linaittech;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

    public static void main(String[] args) {
        
        ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”);
        
        Mirek mireczek = (Mirek) context.getBean(“mirek”);
        mireczek.mirekMethod();

    }

}

Mirek.java

package com.linaittech;

public class Mirek {
    
    private Murek mureczek;
    private Burek bureczek;
    
    public Mirek(Murek mureczek, Burek bureczek) {
        
        System.out.println(“We are inside the Mirek constructor.” );
        this.mureczek = mureczek;
        this.bureczek = bureczek;
    }
    
    public void mirekMethod() {
        mureczek.murekMethod();
        bureczek.burekMethod();
        }

}

Murek.java

package com.linaittech;

public class Murek {
    
    public Murek(){
        System.out.println(“We are inside the Murek constructor.” );
    }
    
    public void murekMethod() {
        System.out.println(“We are inside the murekMethod.” );
        }

}

Burek.java

package com.linaittech;

public class Burek {
    
    public Burek(){
        System.out.println(“We are inside the Burek constructor.” );
    }
    
    public void burekMethod() {
        System.out.println(“We are inside the burekMethod.” );
        }

}

Beans.xml

<beans xmlns=”http://www.springframework.org/schema/beans&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”&gt;

<!– mirek bean definition –>

<bean id=”mirek” class=”com.linaittech.Mirek”>
<constructor-arg ref=”murek”/>
<constructor-arg ref=”burek”/>
</bean>

<!– murek bean definition –>

<bean id=”murek” class=”com.linaittech.Murek”>
</bean>

<!– burek bean definition –>

<bean id=”burek” class=”com.linaittech.Burek”>
</bean>

</beans>

You can run it and see the output:

gru 09, 2013 1:19:57 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1f1bf46: startup date [Mon Dec 09 13:19:57 CET 2013]; root of context hierarchy
gru 09, 2013 1:19:57 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Beans.xml]
gru 09, 2013 1:19:57 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@19039f5: defining beans [mirek,murek,burek]; root of factory hierarchy
We are inside the Murek constructor.
We are inside the Burek constructor.
We are inside the Mirek constructor.
We are inside the murekMethod.
We are inside the burekMethod.

The red lines is the most important for us. We injected two methods (murekMethod and burekMethod) from two beans (Murek and Burek) into the Mirek bean. We used the constructor in the Mirek bean, and all was managed by Beans.xml.

Dependency Injection in Spring Framework

Dependency Injection in Spring Framework

Dependency Injection is a very important thing in Java EE, especially when we use Spring Framework. In short, control and dependency are kept in a XML configuration file, not in a Java file as in a normal Java class is. The flow of control is inverted because it’s in an external system that manages all dependencies. So let’s see all the DI ways that can be used in our projects.

0/ with using a normal Java style

package com.linaittech;

public class Mirek {

private Murek mureczek;

public Mirek(){

mureczek = new Murek();

}

}

All who work with Java language know this style. Desktop apps use it. But Java EE require somewhat different solution.

1/ with using an @Inject annotation in the property to be injected

package com.linaittech;

import javax.inject.Inject;

public class Mirek {

@Inject

private Murek mureczek;

 }

We import the Inject interface, then in the Mirek class, we use Dependency Injection. The @Inject annotation tell us that the field mureczek comes from the Murek class. In other words, it’s injected from Murek to Mirek.

2/ with using the setter method

package com.linaittech;

import javax.inject.Inject;

public class Mirek {

private Murek mureczek

@Inject

public void setMureczek(Murek mureczek{

this.mureczek = mureczek

}

}

So we can use the setter method, too. Again, we import the Inject interface; we have the @inject annotation; but we send the field mruczek from the class Murek to the setMureczek setter method. It’s clear.

3/ with using the constructor method

package com.linaittech;

import javax.inject.Inject;

public class Mirek {

private final Murek mureczek

@Inject

public Mirek(Murek mureczek)

this.mureczek = mureczek

}

}

The same mechanism, but this time we use the constructor. However, we can only have one such constructor (with Dependency Injection).

4/ with using @Any qualifier

package com.linaittech;

import javax.enterprise.inject.Any;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;

public class Mirek {

@Inject

public void getAllBeanImplement(@Any Instance<Murek> beans) {

for (Murek mureczek : beans) {

System.out.println(mureczek.getClass().getCanonicalName());

}

}

}

We have two annotations: @Inject and @Any. We can use the @Any qualifier when we have multiple implementations of one interface and we want to inject them all. Using this annotation the container will inject all implementations of the specified interface. It’s an important difference. We use for loop to go through all the implementations of our interface. Then, we can use such an object to get to its methods or variables.

5/ with using proxies

The proxy handles all calls to the injected bean. It’s a very transparent method. The proxy is an extended bean class with all non private methods overridden. Primitive types cannot be injected. Your bean class must have a non-private default constructor and must not be final nor have final methods.

Sometimes, we can mix DI types if need be. However, remember that you should use constructors with DI for mandatory dependencies and setters with DI for optional dependencies. It’s a good way of programming.

Inheritance of Spring Beans

 Inheritance of Spring Beans

We have five files in our Spring application:

MainApp.java

package com.linaittech2;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”);

Mirek objectA = (Mirek) context.getBean(“mirek”);
objectA.getMessage1();

Murek objectB = (Murek) context.getBean(“murek”);
objectB.getMessage1();
objectB.getMessage2();

Burek objectC = (Burek) context.getBean(“burek”);
objectC.getMessage1();
objectC.getMessage2();
objectC.getMessage3();

}

}

Mirek.java

package com.linaittech2;

public class Mirek {

private String message1;
private String message2;

public void setMessage1(String message) {
this.message1 = message;
}

public void setMessage2(String message) {
this.message2 = message;
}

public void getMessage1() {
System.out.println(“Message1 from Mirek : ” + message1);
}

public void getMessage2() {
System.out.println(“Message2 from Mirek : ” + message2);
}

}

Murek.java

package com.linaittech2;

public class Murek {

private String message1;
private String message2;
private String message3;

public void setMessage1(String message){
this.message1 = message;
}

public void setMessage2(String message){
this.message2 = message;
}

public void setMessage3(String message) {
this.message3 = message;
}

public void getMessage1(){
System.out.println(“Message1 from Murek : ” + message1);
}

public void getMessage2(){
System.out.println(“Message2 from Murek : ” + message2);
}

public void getMessage3() {
System.out.println(“Message3 from Murek : ” + message3);
}

}

Burek.java

package com.linaittech2;

public class Burek {

private String message1;
private String message2;
private String message3;

public void setMessage1(String message){
this.message1 = message;
}

public void setMessage2(String message){
this.message2 = message;
}

public void setMessage3(String message){
this.message3 = message;
}

public void getMessage1(){
System.out.println(“Message1 from Burek : ” + message1);
}

public void getMessage2(){

System.out.println(“Message2 from Burek : ” + message2);
}

public void getMessage3(){
System.out.println(“Message3 from Burek : ” + message3);
}

}

Beans.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<beans xmlns=”http://www.springframework.org/schema/beans&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”&gt;

<bean id=”mirek” parent=”murek”>
<property name=”message1″ value=”mureczek!”/>
</bean>

<bean id=”murek”>
<property name=”message1″ value=”burek!”/>
<property name=”message2″ value=”burki!”/>
</bean>

<bean id=”burek” parent=”murek”>
<property name=”message1″ value=”murek!”/>
<property name=”message3″ value=”murki!”/>
</bean>

</beans>

Output:

gru 03, 2013 2:04:23 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5bcf3a: startup date [Tue Dec 03 14:04:23 CET 2013]; root of context hierarchy
gru 03, 2013 2:04:24 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Beans.xml]
gru 03, 2013 2:04:25 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@7fb9e2: defining beans [mirek,murek,burek]; root of factory hierarchy
Message1 from Mirek : mureczek!
Message1 from Murek : burek!
Message2 from Murek : burki!
Message1 from Burek : murek!
Message2 from Burek : burki!
Message3 from Burek : murki!

The output presents us the mechanism of inheritance. It’s somewhat different than in ordinary Java classes, because the Beans.xml file is very important in this process, but the idea is the same: the child bean can override or add values from the parent one.

You can Beans.xml write in other way. We can make a Bean Definition Template for your application. And child beans can use it. In the Bean Definition Template, there’s no class attribute, but an abstract attribute with its value set to “true”.

<?xml version=”1.0″ encoding=”UTF-8″?>

<beans xmlns=”http://www.springframework.org/schema/beans&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”&gt;

<bean id=”beanDefTemplate” abstract=”true”>
<property name=”message1″ value=”Mirek!”/>
<property name=”message2″ value=”Burek!”/>
<property name=”message3″ value=”Murek!”/>
</bean>

<bean id=”burek” parent=”beanDefTemplate”>
<property name=”message1″ value=”Mirek!”/>
<property name=”message3″ value=”Murek!”/>
</bean>

</beans>

Bean Definition Template is simply an abstract bean. It is similar to an abstract class in Java – it can’t be instantiated, only child beans can use data.

Check Your openSuse System Temperature

Check Your openSuse System Temperature

Sometimes, it’s important to check the system temperature in your Operating System.

1/ Install a hddtemp tool; for openSuse go to:

http://software.opensuse.org/package/hddtemp

2/ Install a psensor GUI tool, for openSuse go to:

http://software.opensuse.org/package/psensor

This package include lm-sensors, so you don’t have to install it before installing psensor.

3/ open your console and write the command to detect the sensors in your system

sensors-detect

4/ write the command to get some temperature data:

psensor

5/ A GUI application pop up. You see the the graph and temperature for:

temp1

Core0

Core1

It can be different because it depends on the sensor have been detected.

Alas, there’s no data for NVidia GPU (licensing problem). There’s no date for HDDs either, but you can just write the command:

hddtemp your/disk/path

For example:

hddtemp /dev/sda

the output is:

/dev/sda: Hitachi HTS541680J83A00: 38°C

You can also write the command:

sensors

the output is:

acpitz-virtual-0
Adapter: Virtual device
temp1:        +65.5°C  (crit = +99.0°C)

coretemp-isa-0000
Adapter: ISA adapter
Core 0:       +62.0°C  (high = +100.0°C, crit = +100.0°C)
Core 1:       +64.0°C  (high = +100.0°C, crit = +100.0°C)

In this way, you can check your system temperature for: CPU (for each core) and HDD.

Bean Post Processors in Spring

Bean Post Processors in Spring

Spring beans are very flexible and versatile technology. Thanks to that, you can develop your Spring application as you want. One of the best solutions in Spring is Post Processors.

– you can provide your application with custom logic by implementing BeanPostProcessor interface. You can do a custom modification

– if you have more BeanPostProcessor interfaces, you can control the order they are implemented by implementing Order interface

Spring IoC Container instantiates a bean instance and then BeanPostProcessor interfaces do their work

ApplicationContext  detects any beans automatically. They are defined with implementation of theBeanPostProcessor interface. ApplicationContext registers these beans as post-processors, and they are called appropriately by the container during bean creation

package com.linaittech;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.BeansException;

public class Mirello implements BeanPostProcessor {

public Object postProcessBeforeInitialization(Object beanObject, String beanName) throws BeansException {

System.out.println(“Before the bean initialization : ” + beanName);

return beanObject;

}

public Object postProcessAfterInitialization(Object beanObject, String beanName) throws BeansException {

System.out.println(“After the bean initialization : ” + beanName);

return beanObject;

}

}

The class Mirello implements BeanPostProcessor interface to use. We import the interface from org.springframework.beans.factory.config.BeanPostProcessor to use the two methods: postProcessBeforeInitialization i postProcessAfterInitialization.

postProcessBeforeInitialization is applied to a new bean instance before any bean initialization callbacks. In other words, it’s used to be sure required actions are taken before initialization.

postProcessAfterInitialization is applied to a new bean instance after any bean initialization callbacks. In other words, it’s used to be sure required actions are taken after initialization but before destruction.

Both these methods take two arguments:

beanObject – the instance of our bean

beanName – the name of our bean

The life cycle of a Spring bean with Post Processor is following :

1/ BeanPostProcessor.postProcessBeforeInitialization()

2/ init()

3/ BeanPostProcessor.postProcessAfterInitialization()

4/ destroy()

So thanks to BeanPostProcessor, we can do something before our bean initialization and before our bean destruction. Sometimes, it’s very useful.

ApplicationContext or AbstractApplicationContext in Spring Framework

ApplicationContext or AbstractApplicationContext in Spring Framework

With using the ApplicationContext interface.

package com.linaittech1;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class MainApp {

    public static void main(String[] args) {
       
        ApplicationContext context = new FileSystemXmlApplicationContext (“file:/home/poganin/worksSpringer/Spring2/src/Beans.xml”);
        Mirek obj = (Mirek) context.getBean(“mirek”);
        obj.getMessage();
       
        ApplicationContext context1 = new FileSystemXmlApplicationContext (“file:/home/poganin/worksSpringer/Spring2/src/Beans.xml”);
        Lak obj1 = (Lak) context1.getBean(“lak”);
        obj1.getNum1();
        obj1.getNum2();
        obj1.getSum();
       
    }

}

With using the AbstractApplicationContext interface.

package com.linaittech1;

import org.springframework.context.AbstractApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class MainApp {

    public static void main(String[] args) {
        
        AbstractApplicationContext context = new FileSystemXmlApplicationContext (“file:/home/poganin/worksSpringer/Spring2/src/Beans.xml”);
        Mirek obj = (Mirek) context.getBean(“mirek”);
        obj.getMessage();
        context.registerShutdownHook();
        
        AbstractApplicationContext context1 = new FileSystemXmlApplicationContext (“file:/home/poganin/worksSpringer/Spring2/src/Beans.xml”);
        Lak obj1 = (Lak) context1.getBean(“lak”);
        obj1.getNum1();
        obj1.getNum2();
        obj1.getSum();
        context1.registerShutdownHook();
        
    }

}

You probably see the difference. With AbstractApplicationContext, we have a great possibility to shutdown our bean. Sometimes, it’s simply good to use the second method.

Spring Java Beans in XML Configuration File

Spring Java Beans in XML Configuration File

The XML configuration file called usually Beans.xml look in this way:

<?xml version=”1.0″ encoding=”UTF-8″?>

<beans xmlns=”http://www.springframework.org/schema/beans&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”&gt;

</beans>

Inside, we can write many things. The most important is our beans definitions. we can do that in many ways:

A simple bean definition looks:

<bean id=”…”>

Bean configuration

</bean>

A bean definition with lazy init set on looks:

<bean id=”…” lazy-init=”true”>

Bean configuration

</bean>

A bean definition with initialization method looks:

<bean id=”…” init-method=”…”>

Bean configuration

</bean>

A bean definition with destruction method looks:

<bean id=”…” destroy-method=”…”>

Bean configuration

</bean>

So we can see some properties that are used in Beans.xml files.

class – the class of your bean

name – your bean identifier that is unique

scope – the scope of your bean objects

constructor-arg

properties

autowiring mode

lazy-initailization mode – your bean instance is created by IoC container when needed

initialization method – A callback to be called just after all necessary properties on the bean have been set by the container

destruction method – A callback to be used when the container containing the bean is destroyed

Let’s look at the scope attribute.

singleton – a single instance per Spring IoC container; it’s default

prototype – any number of object instances

Scopes connected with Spring ApplicationContext:

request

session

global-session

The example of the bean with singleton scope:

<?xml version=”1.0″ encoding=”UTF-8″?> <beans xmlns=”http://www.springframework.org/schema/beans&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”&gt;

<bean id=”helloWorld” scope=”singleton”>
</bean>

</beans>

The example of the bean with prototype scope:

<?xml version=”1.0″ encoding=”UTF-8″?> <beans xmlns=”http://www.springframework.org/schema/beans&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”&gt;

<bean id=”helloWorld” scope=”prototype”>
</bean>

</beans>

Life cycle of Spring bean

There are many things in the life cycle of Spring beans, but the most important are initialization and destruction. That’s why, we have init-method and destroy-method.

The initialization of our bean can be done in this way:

In Bean.xml, we have the following code:

<bean id=”mirelka” class=”com.linaittech.Mirelka” init-method=”initBean”/>

In the Mirelka.java file (our bean), we have the following code:

public class Mirelka {
public void initBean() {
our bean initialization code
}
}

The destruction of our bean can be done in this way:

In Bean.xml, we have the following code:

<bean id=”mirelka” class=”com.linaittech.Mirelka” destroy-method=”destroyBean”/>

In the Mirelka.java file (our bean), we have the following code:

public class Mirelka {
public void destroyBean() {
our bean destruction code
}
}

When we have many initialization and destruction methods, we don’t have to do it in each bean definition; we simply use this trick:

<beans xmlns=”http://www.springframework.org/schema/beans&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd&#8221; default-init-method=”initBean” default-destroy-method=”destroyBean”>
<bean id=”…”>
Bean configuration
</bean>
</beans>

We see that <beans …> </beans> include default-init-method and default-destroy-method parameters.