Prevent Spring AOP from closing my Stream?

dan*_*niu 1 java aop spring spring-aop

I'm using the following construction (simplified):

@Component
class RuleProvider {
    public Stream<String> getRules() {
        return Stream.of("r1", "r2", "r3");
    }
}

@Service
class RuleService {
    @Autowired RuleProvider ruleProvider;
    public void evaluateRules() {
        ruleProvider.getRules().foreach(System.out::println);
    }
}
Run Code Online (Sandbox Code Playgroud)

and I use Spring AOP to perform logging. Now I'd like to log all the rules that are handed to the service. In general, this should do it:

@Aspect
class LoggingAspect {
    @AfterReturning(value="execution(* *..RuleProvider.getRules(*))",
                    returning="rules")
    void logRules(JoinPoint jp, Stream<String> rules) {
        Logger logger = LoggerFactory.getLogger(jp.getTarget().getClass());
        rules.peek(rule -> logger.debug("evaluating {}", rule);
    }
}
Run Code Online (Sandbox Code Playgroud)

This should work - the aspect is evaluated, registers the peek intermediate operation, and once the foreach() terminal op is performed, the logging should also to done.

However, when I run this, the Stream seems to get closed after the aspect has run - I get a "stream has already been operated upon or closed" in the service method.

Why is the Stream being closed? Is there anything I can do against that?

Kli*_*cou 5

流没有关闭,但是很显然,错误消息说的完全是“已经被操作了”。考虑peek通常如何使用:

Stream.of(...)
    .peek(...)
    .other_operations(...);
Run Code Online (Sandbox Code Playgroud)

请注意,other_operations()作用于peek()返回的Stream,而不作用于原始流。您使用方面进行的操作与此类似:

Stream s = Stream.of(...);
s.peek(...);
s.other_operations(...);
Run Code Online (Sandbox Code Playgroud)

解决此问题的方法是替换返回值,例如通过使用@Around方面。