欢迎光临
我们一直在努力

Dubbo的高级特性自动包装Wrapper

在Maven中引入Dubbo的坐标

<!– Apache Dubbo –>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
<version>2.7.8</version> <!– 请使用最新版本 –>
</dependency>

创建扩展点接口

package com.tairui.interfaces;

import org.apache.dubbo.common.extension.SPI;

/**
* @author
* @date 2026/2/27 16:06
*/
@SPI
public interface SystemInterface {
void test();
}

创建扩展点

package com.tairui.interfaces.impl;

import com.tairui.interfaces.SystemInterface;

/**
* @author
* @date 2026/2/27 16:07
*/
public class Linux implements SystemInterface {
@Override
public void test() {
System.out.println("Linux系统启动中…");
}
}

package com.tairui.interfaces.impl;

import com.tairui.interfaces.SystemInterface;

/**
* @author
* @date 2026/2/27 16:08
*/
public class Windows implements SystemInterface {
@Override
public void test() {
System.out.println("Windows系统启动中…");
}
}

创建自动包装类Wrapper

Wrapper和普通扩展点一样都是实现扩展点接口,通过带有扩展点接口的有参构造区分是否是Wrapper

package com.tairui.interfaces.impl;

import com.tairui.interfaces.SystemInterface;

/**
* @author
* @date 2026/2/28 8:33
*/
public class IOSWarapper implements SystemInterface {

public SystemInterface systemInterface;

public IOSWarapper(SystemInterface systemInterface) {
this.systemInterface = systemInterface;
}

@Override
public void test() {
System.out.println("IOS 增强前。。。");
systemInterface.test();
System.out.println("IOS 增强后。。。");
}
}

在META-INF/dubbo目录下创建以扩展点接口全限命名的文件(com.tairui.interfaces.SystemInterface)

Linux = com.tairui.interfaces.impl.Linux
windows = com.tairui.interfaces.impl.Windows
warepper=com.tairui.interfaces.impl.IOSWarapper

创建测试类

import com.tairui.interfaces.SystemInterface;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.config.ReferenceConfig;

import java.util.ServiceLoader;

/**
* @author
* @date 2026/2/27 16:10
*/
public class SystemTest {

public static void main(String[] args) {
// 使用Dubbo加载服务
ExtensionLoader<SystemInterface> extensionLoader = ExtensionLoader.getExtensionLoader(SystemInterface.class);
SystemInterface windows = extensionLoader.getExtension("windows");
windows.test();
SystemInterface Linux = extensionLoader.getExtension("Linux");
Linux.test();
}

}

赞(0)
未经允许不得转载:171主机测评 » Dubbo的高级特性自动包装Wrapper
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址