javaspringaopaspects

Why is this Spring Aspect not printing as it should with method parameter?


Let me first foremention, the problem I'm facing is with the
interceptThoughts(String thoughts)
method, from the first code block, not printing

I'm running a tutorial from Spring in Action. There's a Magician class that implements MindReader interface with methods interceptThoughts(String thoughts) and getThoughts()

@Aspect
public class Magician implements MindReader {

    private String thoughts;

    @Pointcut("execution(* com.underdogdevs.myspringaspectj." 
            + "Thinker.thinkOfSomething(String)) && args(thoughts)")
    public void thinking(String thoughts) {
    }

    @Override
    @Before("thinking(thoughts)") 
    public void interceptThoughts(String thoughts) {
        System.out.println("Intercepting volunteer's thoughts : " + thoughts);  
        this.thoughts = thoughts;
    }

    @Override
    public String getThoughts() {
        return thoughts;
    }
}

The aspect is supposed to read the mind of a Volunteer that implements Thinker interface, with method thinkOfSomething(String thoughts)

public class Volunteer implements Thinker {

    private String thoughts;

    @Override
    public void thinkOfSomething(String thoughts) {
        this.thoughts = thoughts;
        System.out.println("Something");
    }

    public String getThoughts() {
        return thoughts;
    }
}

I have my java BeanConfig with the Magician and the Volunteer

@Configuration
public class BeanConfig {

    @Bean
    public MindReader magician() {
        return new Magician();
    }

    @Bean
    public Thinker volunteer() {
        return new Volunteer();
    }  
}

And I'm trying to run it to get the Magician method to print the line in the interceptThoughts method

public class App {
    public static void main(String[] args) {
        ApplicationContext context = 
                new ClassPathXmlApplicationContext("spring-idol.xml");

        System.out.println();
        Thinker volunteer = (Thinker)context.getBean("volunteer");
        volunteer.thinkOfSomething("This is what I'm thinking");
    }
}

The problem is the @Before from the Magician aspect isn't printing as it should. Am I missing something here? Why is it not printing? I have other aspect methods that take no arguments and run just fine. Am I not passing the parameter value correctly?


Solution

  • try this

    @Configuration
    public class BeanConfig {
    
        @Bean
        public Magician magician() {
            return new Magician();
        }
    ...
    

    I don't know whether it is in Spring's docs, but it's clear that when Spring analizes return type of magician() and when it is MindReader Spring cannot see any annotation on it.