Backend Development 13 min read

Using the Pie Framework for Responsibility Chain Development in Java

This article introduces the Pie framework, a Java-based implementation of the responsibility‑chain design pattern, demonstrates how to integrate it with Maven, shows step‑by‑step code examples for handlers, outbound factories, bootstrapping, and global exception handling, and explains its benefits for clean, maintainable backend development.

JD Tech
JD Tech
JD Tech
Using the Pie Framework for Responsibility Chain Development in Java

Design patterns are widely used in software development to improve code readability, maintainability, and extensibility. The responsibility‑chain pattern, common in frameworks like SpringMVC and Netty, is implemented in the Pie framework, which extracts Netty's chain code and provides an API compatible with Netty.

To get started, add the Pie dependency to your Maven project:

<dependency>
    <groupId>com.feiniaojin.ddd.ecosystem</groupId>
    <artifactId>pie</artifactId>
    <version>1.0</version>
</dependency>

Pie offers an OutboundFactory interface to create default result objects. An example implementation:

public class OutFactoryImpl implements OutboundFactory {
    @Override
    public Object newInstance() {
        Result result = new Result();
        result.setCode(0);
        result.setMsg("ok");
        return result;
    }
}

Three handlers illustrate typical responsibilities:

public class CheckParameterHandler implements ChannelHandler {
    private Logger logger = LoggerFactory.getLogger(CheckParameterHandler.class);
    @Override
    public void channelProcess(ChannelHandlerContext ctx, Object in, Object out) throws Exception {
        logger.info("参数校验:开始执行");
        if (in instanceof ArticleTitleModifyCmd) {
            ArticleTitleModifyCmd cmd = (ArticleTitleModifyCmd) in;
            Objects.requireNonNull(cmd.getArticleId(), "articleId不能为空");
            Objects.requireNonNull(cmd.getTitle(), "title不能为空");
            Objects.requireNonNull(cmd.getContent(), "content不能为空");
        }
        logger.info("参数校验:校验通过,即将进入下一个Handler");
        ctx.fireChannelProcess(in, out);
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause, Object in, Object out) throws Exception {
        logger.error("参数校验:异常处理逻辑", cause);
        Result re = (Result) out;
        re.setCode(400);
        re.setMsg("参数异常");
    }
}

public class ArticleModifyTitleHandler implements ChannelHandler {
    private Logger logger = LoggerFactory.getLogger(ArticleModifyTitleHandler.class);
    @Override
    public void channelProcess(ChannelHandlerContext ctx, Object in, Object out) throws Exception {
        logger.info("修改标题:进入修改标题的Handler");
        ArticleTitleModifyCmd cmd = (ArticleTitleModifyCmd) in;
        String title = cmd.getTitle();
        logger.info("修改标题:title={}", title);
        logger.info("修改标题:执行完成,即将进入下一个Handler");
        ctx.fireChannelProcess(in, out);
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause, Object in, Object out) throws Exception {
        logger.error("修改标题:异常处理逻辑");
        Result re = (Result) out;
        re.setCode(1501);
        re.setMsg("修改标题发生异常");
    }
}

public class ArticleModifyContentHandler implements ChannelHandler {
    private Logger logger = LoggerFactory.getLogger(ArticleModifyContentHandler.class);
    @Override
    public void channelProcess(ChannelHandlerContext ctx, Object in, Object out) throws Exception {
        logger.info("修改正文:进入修改正文的Handler");
        ArticleTitleModifyCmd cmd = (ArticleTitleModifyCmd) in;
        logger.info("修改正文,content={}", cmd.getContent());
        logger.info("修改正文:执行完成,即将进入下一个Handler");
        ctx.fireChannelProcess(in, out);
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause, Object in, Object out) throws Exception {
        logger.error("修改标题:异常处理逻辑");
        Result re = (Result) out;
        re.setCode(1502);
        re.setMsg("修改正文发生异常");
    }
}

The BootStrap class assembles the chain and executes it. A minimal example:

public class ArticleModifyExample1 {
    private static final Logger logger = LoggerFactory.getLogger(ArticleModifyExample1.class);
    public static void main(String[] args) {
        ArticleTitleModifyCmd dto = new ArticleTitleModifyCmd();
        dto.setArticleId("articleId_001");
        dto.setTitle("articleId_001_title");
        dto.setContent("articleId_001_content");
        BootStrap bootStrap = new BootStrap();
        Result result = (Result) bootStrap
                .inboundParameter(dto)
                .outboundFactory(new ResultFactory())
                .channel(new ArticleModifyChannel())
                .addChannelHandlerAtLast("checkParameter", new CheckParameterHandler())
                .addChannelHandlerAtLast("modifyTitle", new ArticleModifyTitleHandler())
                .addChannelHandlerAtLast("modifyContent", new ArticleModifyContentHandler())
                .process();
        logger.info("result:code={},msg={}", result.getCode(), result.getMsg());
    }
}

Exception handling can be done per handler via exceptionCaught , or globally by adding a final handler that extends ChannelHandlerAdapter :

public class ExceptionHandler extends ChannelHandlerAdapter {
    private Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause, Object in, Object out) throws Exception {
        logger.error("异常处理器中的异常处理逻辑");
        Result re = (Result) out;
        re.setCode(500);
        re.setMsg("系统异常");
    }
}

By appending ExceptionHandler to the chain, any uncaught exceptions from earlier handlers are routed to this global handler, ensuring a unified error response.

In summary, the Pie framework provides a quick‑start, low‑coupling solution for implementing the responsibility‑chain pattern in Java backend projects, improving code modularity, readability, and error management.

design patternsJavabackend developmentException HandlingMavenresponsibility chainframework
JD Tech
Written by

JD Tech

Official JD technology sharing platform. All the cutting‑edge JD tech, innovative insights, and open‑source solutions you’re looking for, all in one place.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.