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:
- [Solved] HttpPost Call https Interface error: PKIX path building failed
- Abstract method and static method of java interface
- try-with-resource automatically closes the resources of the AutoClosable interface
- [Solved] BindingException: Type interface XXX is not known to the MapperRegistry
- [Solved] SpringBoot Task Error: Unexpected error occurred in scheduled task
- jasypt springboot Error: Error creating bean with name ‘enableEncryptablePropertySourcesPostProcessor’ defined in class path resource
- Springboot controls the startup of rabbitmq through configuration files
- Problems in springboot upgrade 2.4.0: when allowcredentials is true, allowedorigins cannot contain the specia
- [Solved] springboot Error: Error creating bean with name ‘configurationPropertiesBeans‘ defined in class path
- [Solved] SpringBoot Project Startup Error: Field userMapper in com.demo.controller.MemberController required a bean of type ‘c
- [Solved] Springboot Error: Error creating bean with name ‘dataSource‘ defined in class path resource
- Springboot startup error: Field elasticsearchRestTemplate in cn.lili.modules.material.serviceImpl.QrMaterialServiceImpl required a bean of type
- SpringBoot integrates Es error: Error creating bean with name ‘restHighLevelClient‘ defined in class path resource
- The problem of date format conversion between springboot and front end
- [Solved] IDEA springboot Startup Error: java.lang.UnsatisfiedLinkError: no tcnative-1 in java.library.path
- NULL value exception occurs when freemarker renders the page globally in the springboot project
- [Solved] Springboot2.x ElasticSearch Error: availableProcessors is already set to [4], rejecting [4]
- Springboot startup error: err config is disabled command (Redis Disables Config command)
- [Solved] SpringBoot Startup Error: Description:Web server failed to start. Port 9090 was already in use.(win10)
- SpringBoot+Swagger Error: 403 Forbidden [How to Solve]