Spring in Beanpostprocessors "2" elegant implementation of business separation

Source: Internet
Author: User
1 Overview
Beanpostprocessors can do some preprocessing of the bean before the spring IOC container initializes the managed Bean, property settings, or release the resource itself before the container destroys the managed bean. The article "Beanpostprocessors in Spring" 1 "Simple preprocessing" is illustrated by an example. This article describes a specific case, elegant implementation of business separation.


2 base class

Imagine a system in a number of modules, for the module and have different operation commands for different modules of different command scenes, there will be different processing. Of course it is possible to judge by if else, but the readability and elegance are too poor. The following is an elegant implementation of the annotation +beanpostprocessors approach.

"1" Annotation class

Package com.xy.annotation;
Import Java.lang.annotation.ElementType;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;
Import Java.lang.annotation.Target;

@Target (Elementtype.type)
@Retention (retentionpolicy.runtime) public
@interface module {

	/**
	 * block number
	 * * Short
	ModuleID ();
}


Import Java.lang.annotation.ElementType;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;
Import Java.lang.annotation.Target;

@Target (Elementtype.method)
@Retention (retentionpolicy.runtime) public
@interface Bizcommand {

	/**
	 * Command Number
	 *
	/short cmdId ();
}

"2" constant class

Package com.xy.constants;
Public interface Constantcmd {

	//Add public short
	add = 1;

	Delete public short
	delete = 2;
}

Public interface Constantmodule {

	//Student Module public short
	STUDENT = 1;
	
	Teacher Module public short
	TEACHER = 2;
}

"3" Business class

Package com.xy.service;
Import Com.xy.annotation.BizCommand;
Import Com.xy.annotation.Module;
Import COM.XY.CONSTANTS.CONSTANTCMD;
Import Com.xy.constants.ConstantModule;

@Module (ModuleID = constantmodule.student) Public
interface Stuservice {

	@BizCommand (cmdId = constantcmd.add) Public
	void Add (String name);
	
	@BizCommand (cmdId = constantcmd.delete) public
	void DELETE (String name);


Import org.springframework.stereotype.Component;

@Component//This class needs to be spring managed public
class Stuserviceimpl implements Stuservice {public

	void Add (String name) C15/>system.out.println ("I am student Add method.add name:" + name);
	}

	public void Delete (String name) {
		System.out.println ("I am student Delete method.delete name:" + name);
	}



3 Core Classes

The general idea is to use the module number + command number to correspond to different methods and implementation classes, and the method and implementation classes are in the corresponding list.

Incoming module number and command number, you can get the corresponding method name and implementation class, you can execute.

Package Com.xy.scanner;
Import Java.lang.reflect.Method;
Import org.springframework.beans.BeansException;
Import Org.springframework.beans.factory.config.BeanPostProcessor;
Import org.springframework.stereotype.Component;
Import Com.xy.annotation.BizCommand;

Import Com.xy.annotation.Module; @Component//This class also needs to be spring managed public class Bizscanner implements Beanpostprocessor {public Object Postprocessbeforeiniti
	Alization (Object Bean, String beanname) throws beansexception {return bean; public object Postprocessafterinitialization (object bean, String beanname) throws Beansexception {//container-managed class information (Stus Erviceimpl) class<?

		Extends object> clazz = Bean.getclass ();

		The interface implemented by this class (Stuservice) class<?>[] interfaces = Clazz.getinterfaces ();  if (null!= interfaces && interfaces.length > 0) {for (class<?> interface:interfaces) {//
				Get interface annotation//module information Module module = interface.getannotation (Module.class);
				if (null = = module)	Continue
				All methods of the interface method[] methods = Interface.getmethods (); if (null!= methods && methods.length > 0) {for (method Method:methods) {//Command information Bizcomman
						D Bizcommand = method.getannotation (Bizcommand.class);

						if (null = = Bizcommand) continue;
						Module number Short ModuleID = Module.moduleid ();
						Command number Short cmdId = Bizcommand.cmdid (); if (Bizinvokermanager.getinvoker (ModuleID, cmdId) = = null) {Bizinvokermanager.addinvoker (ModuleID, CmdId, Bizinvok
						Er.valueof (method, Bean));
						else {System.out.println ("repeat command:" + "module:" + ModuleID + "" + "CmdId:" + cmdId);
	}}} return bean;
}} import java.lang.reflect.InvocationTargetException;

Import Java.lang.reflect.Method;

	/** * Command Executor/public class Bizinvoker {/** * methods * * method;

	/** * Target object (Implementation Class)/private object target; /** * Package Actuator * * @param method Com.xy.service.StuSerVice.add * @param target COM.XY.SERVICE.STUSERVICEIMPL@273E07BD * @return Actuator/public static Bizinvoker Valueo
		F (method, Object target) {bizinvoker invoker = new Bizinvoker ();
		Invoker.setmethod (method);
		Invoker.settarget (target);
	return invoker;  /** * Calling Method * * @param paramvalues parameter * @return Execution result/public object Invoke (Object ... paramvalues) {try {//Method methods Com.xy.service.StuService.add//target target COM.XY.SERVICE.STUSERVICEIMPL@273E07BD return METHOD.I
		Nvoke (target, paramvalues);
		catch (Illegalaccessexception e) {e.printstacktrace ();
		catch (IllegalArgumentException e) {e.printstacktrace ();
		catch (InvocationTargetException e) {e.printstacktrace ();
	return null;
	Public method GetMethod () {return method;
	public void Setmethod (method method) {This.method = method;
	Public Object Gettarget () {return target;
	public void Settarget (Object target) {this.target = target;
}
}

Import Java.util.HashMap;

Import Java.util.Map; /** * Command Executor Manager/public class Bizinvokermanager {/** * command caller (1th short is module number, 2nd short is command number)/private static MAP&L T

	Short, map<short, bizinvoker>> invokers = new Hashmap<short, Map<short, bizinvoker>> (); /** * Add Command Call * * @param module number * @param cmd command number * @param invoker caller/public static void Addinvoker (SH
		Ort ModuleID, short cmdId, Bizinvoker invoker) {map<short, bizinvoker> Map = Invokers.get (ModuleID);
			if (null = = map) {map = new hashmap<short, bizinvoker> ();
		Invokers.put (ModuleID, map); } map.put (CmdId, invoker); Change the reference, save the command number in}/** * GET command Call * * @param module Modular number * @param cmd command number */public static Bizinvoker Getinvoker (Short ModuleID, short cmdId)
		{map<short, bizinvoker> Map = Invokers.get (ModuleID);
		if (map!= null) {return map.get (cmdId);
	return null; }

}

4 Spring Files

<context:component-scan base-package= "Com.xy.scanner"/>
<context:component-scan base-package= " Com.xy.service "/>

5 test

Package com.xy.test;

Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;
Import COM.XY.CONSTANTS.CONSTANTCMD;
Import Com.xy.constants.ConstantModule;
Import Com.xy.scanner.BizInvoker;
Import Com.xy.scanner.BizInvokerManager;

public class Testbean {public

	static void Main (string[] args) {
		ApplicationContext ac = new Classpathxmlapplicati Oncontext ("Applicationcontext.xml");
		System.out.println (AC);

		Bizinvoker invoker1 = Bizinvokermanager.getinvoker (constantmodule.student, constantcmd.add);
		Invoker1.invoke ("Xy1");

		System.out.println ("========================");

		Bizinvoker invoker2 = Bizinvokermanager.getinvoker (constantmodule.student, constantcmd.delete);
		Invoker2.invoke ("Xy2");
	}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.