当前位置:网站首页>Record 5: implement the operation of interface function enhancement in the project through beanpostprocessor;

Record 5: implement the operation of interface function enhancement in the project through beanpostprocessor;

2020-11-10 17:30:39 manyu7741

brief introduction

 Some of the functions already implemented in the project , You may be asked to add additional operation content to the method , For example, how to print the log content in front of it , Or record the time of interface operation , Well done code doesn't want to be changed on a large scale , In this paper, user-defined BeanPostProcessor  Implement the class to complete the current function  (/ Custom annotation / Interceptor / proxy class  / section   We can meet our needs )

Code content

1. Customize SportServiceBeanPostProcessor

public class SportServiceBeanPostProcessor implements BeanPostProcessor {
   
	
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
   
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
   
		//  Project initialization time is just going to be  SportService  Interface implementation class object for the following code enhancement use ;
		if(!(bean instanceof SportService)){
   
			return bean;
		} 
		
		final Object finalBean = bean;
		Map<String,Object> map = new ConcurrentHashMap<>(10); 
		if(null != map.get(beanName)){
   
			return map.get(beanName);
		}
		Class<?>[] interfaces = bean.getClass().getInterfaces();
		// There is no direct return of the interface 
		if(null == interfaces || interfaces.length < 1){
   
			return bean;
		}
		// Execute the following when calling the method of the target object diamante
		Object proxyObj = Proxy.newProxyInstance(this.getClass().getClassLoader(), interfaces, new InvocationHandler() {
   
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   
				Object result = null;
				// Direct execution without enhanced methods 
				if(method.getName().equals("equals") || method.getName().equals("toString")){
   
					result = method.invoke(finalBean, args);
				}else{
   
					// Write the enhanced method to the following code 
					System.out.println("method:" + method.getName());
					result = method.invoke(finalBean, args);
					System.out.println(" current time :" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
				}
				return result;
			}
		});
		map.put(beanName, proxyObj);
		return proxyObj;
	}

}
 Self defined SportServiceBeanPostProcessor  Realization BeanPostProcessor  stay postProcessAfterInitialization  Method through the proxy class to complete the function of the corresponding interface 

2.Config Configure our custom SportServiceBeanPostProcessor

@Configuration
public class Config {
   
	/** *  Inject the corresponding BeanPostProcessor Object content ; *  When the service is started  SportServiceBeanPostProcessor  Of postProcessAfterInitialization  Method  *  According to the conditions we set, intercept those methods that need to be done to enhance the use of  * @author khy * @createTime 2020 year 11 month 10 On the afternoon of Sunday 3:03:36 * @return */
	@Bean
	public SportServiceBeanPostProcessor init(){
   
		SportServiceBeanPostProcessor postProcessor = new SportServiceBeanPostProcessor();
		return postProcessor;
	}
}

3. Need to be enhanced SportService Interface and implementation classes

 Insert picture description here

4.KhyController The code in

@RestController
@RequestMapping("/khy")
public class KhyController {
   

	// The objects injected here remain unchanged , Actually, it is the proxy object we set up 
	@Autowired
	private SportService sportService;
	
	@RequestMapping("/test")
	public String test(){
   
		sportService.run(" The way of learning ");
		sportService.sleep(" good ");
		return " Method execution completed ";
	}
}

summary

After the project is started, the custom SportServiceBeanPostProcessor , But in
postProcessAfterInitialization In the method , Through the proxy object to complete the function of our target object, set the method content to be added in the proxy object . Than our previous article adopt FactoryBean Class enhanced interface The advantage of this approach is that
We can still pass through our @Autowired Annotation injection , In this way, the previously completed code does not need a large range of changes to complete the function implementation .

版权声明
本文为[manyu7741]所创,转载请带上原文链接,感谢