It's been a long time since I posted a post, and I encountered a problem in reality:
in the port multi-dock system, the definitions of multiple dock interfaces are the same, but the specific implementations are different: some use individual implementations, some use general implementations, how to elegantly Solve this problem to facilitate development and post-maintenance? After much deliberation, using SpringAOP and the proxy mode to achieve
[b]The idea is limited, I implore the hero Xiami to put forward a pertinent opinion[/b]
The specific usage is as follows, please see the attachment for the specific code
//------This method is for the CargoSvr interface Proxy implementation class -------------
//This class is called in action or mvc, other implementation classes cannot directly call in action
@Service("cargoSvrProxy")
public class CargoSvrImpl implements CargoSvr {
public CargoSvr svr2;
//@SvrProxy is the annotation method of the proxy class, adding The annotated method will automatically judge which implementation class to call according to the dock code
@SvrProxy(svrName="cargoSvr",proxyName="svr2",interfaceOrder="0")
public void say(String portCode,String cargoNam){
System.out .println("from proxy");
svr2.say(portCode, cargoNam);
}
/**
* Injection, this method needs to inject a concrete implementation class in aop
* @param svr
*/
public void setSvr2(CargoSvr svr) {
this .svr2 = svr;
}
}
//------------ This is the default implementation class. When there is no personality implementation class matching, this implementation class is automatically called
@Service("def_cargoSvr")
public class CargoSvrImpl implements CargoSvr {
public void say(String portCode,String cargoNam){
System.out.print("def_cargoSvr");
}
}
/**
* tf实现类
* @author broker
*
*/
@Service("tf_cargoSvr")
public class CargoSvrImpl implements CargoSvr {
public void say(String portCode,String cargoNam){
System.out.print("tf_cargoSvr");
}
}
/**
* 测试类
* @throws Exception
*/
@Test
public void Test() throws Exception {
cargoSvrProxy.say("@@tf","Hello world");
}
When running the test class, the implementation class say method of cargoSvrProxy adds @SvrProxy to tell AOP that this needs to be processed and implemented in the before phase.
The parameter judgment starts with two @ symbols. When @@ is seen, the following terminal code tf is automatically filtered. AOP finds tf_cargoService and injects it into the setSvr2 of the proxy implementation class according to the rules, thereby calling the say implementation of tf_cargoService
For detailed code and dependency packages, please see the attachment
If you don't understand what I wrote, run the test class SvrServiceTest to see the results.
please correct