Initializingbean Interface & Applicationcontextaware Interface in Springboot

1. InitializingBean

There is only one method in this interface initializingbean, afterpropertieset. This method refers to the method that the spring container actively calls the interface after starting. If a bean implements initializingbean, the method will call the afterpropertieset method after the container instantiates the bean and initializes the bean’s properties. AfterPropertiesSet knows the meaning by the name of the method: it is called after the property of bean is set.

The initialization bean interface source code is as follows:

public interface InitializingBean {

    /**
     * This method is called by the BeanFactory when the bean's properties have been set.
     * This method allows the instance of the bean to perform some initialization actions, which are executed when all the bean properties are finished being set.   
     */
    void afterPropertiesSet() throws Exception;
}

2. ApplicationContextWare

Name with aware, you can know that this interface is actively notified and called by the spring container. The spring container injects the context ApplicationContext when it notifies the implementation class of the interface. There is only one method in the interface:
void setapplicationcontext (ApplicationContext) throws beansexception, that is, after the container is started, ApplicationContext is injected into the method.

The source code of interface applicationcontextware is as follows:

public interface ApplicationContextAware extends Aware {
    void setApplicationContext(ApplicationContext var1) throws BeansException;
}

3. Examples

3.1 enumeration class familyenum

package com.example.demo.blogTest;

public enum FamilyEnum {
    FATHER(45, "father"),
    MOTHER(42, "mother"),
    SON(18, "son");

    private Integer age;
    private String name;
    FamilyEnum(Integer age, String name) {
        this.age = age;
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public String getName() {
        return name;
    }
}

3.2 user defined injection class familyholder

package com.example.demo.blogTest;

import com.example.demo.service.BaseService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
public class FamilyHolder implements InitializingBean, ApplicationContextAware {
    private ApplicationContext applicationContext;
    private Map<FamilyEnum, BaseService> map = new HashMap<>();

    public BaseService getEnum(FamilyEnum familyEnum) {
        return map.get(familyEnum);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        map = applicationContext.getBeansOfType(BaseService.class)
                .values()
                .stream()
                .collect(Collectors.toMap(BaseService::getEnum, Function.identity()));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

3.3 abstract class BaseService

package com.example.demo.service;

import com.example.demo.blogTest.FamilyEnum;

public abstract class BaseService {
    // abstract working class, specific implementation by its successor
    public abstract void myJob();

    public abstract FamilyEnum getEnum();

    // Generic methods, which can also be overridden by inheritors
    public String getName(FamilyEnum person) {
        return person.getName();
    }
}

3.4 Abstract inheritance class fatherservice

package com.example.demo.service;

import com.example.demo.blogTest.FamilyEnum;
import org.springframework.stereotype.Service;

@Service
public class FatherService extends BaseService{
    @Override
    public void myJob() {
        System.out.println("I am a engineer!");
    }

    @Override
    public FamilyEnum getEnum() {
        return FamilyEnum.FATHER;
    }
}

3.5 Abstract inheritance class motherservice

package com.example.demo.service;

import com.example.demo.blogTest.FamilyEnum;
import org.springframework.stereotype.Service;

@Service
public class MotherService extends BaseService{
    @Override
    public void myJob() {
        System.out.println("I am a teacher!");
    }

    @Override
    public FamilyEnum getEnum() {
        return FamilyEnum.MOTHER;
    }
}

3.6 Abstract inheritance class myservice

package com.example.demo.service;

import com.example.demo.blogTest.FamilyEnum;
import org.springframework.stereotype.Service;

@Service
public class MyService extends BaseService{
    @Override
    public void myJob() {
        System.out.println("I am a student!");
    }

    @Override
    public FamilyEnum getEnum() {
        return FamilyEnum.SON;
    }
}

3.7 test class demoapplicationtests

package com.example.demo;

import com.example.demo.blogTest.FamilyEnum;
import com.example.demo.blogTest.FamilyHolder;
import com.example.demo.service.BaseService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
class DemoApplicationTests {
    @Autowired
    private FamilyHolder familyHolder;

    @Test
    void contextLoads() throws ClassNotFoundException {
        // Get all enumeration elements by reflection
        Class<FamilyEnum> clazz = (Class<FamilyEnum>) Class.forName("com.example.demo.blogTest.FamilyEnum");
        FamilyEnum[] enumConstants = clazz.getEnumConstants();
        for (FamilyEnum familyEnum : enumConstants) {
            BaseService baseService = familyHolder.getEnum(familyEnum);
            baseService.myJob();
        }
    }
}

Output results

I am a engineer!
I am a teacher!
I am a student!


Read More: