Search code examples
springaspectjspring-aop

Aspect not working witha spring bean


I am trying to create a simple aspect . Here is my simple spring bean

public class SimpleService {
    public void sayHello(){
        System.out.println("hi");
    }

}

Here is my aspect class

@Aspect
public class SimpleAspect {
    @Before("execution(void sayHello())")
    public void entering(){
        System.out.println("entering..");
    }
}

Here is my configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
         <aop:aspectj-autoproxy/>
<bean id="service" class="com.schatt.service.SimpleService"></bean>

My understanding was that when I try to invoke SimpleService.sayHello() , the before aspect will be called and after that sayHello() will be called.But the aspect is not getting triggered.Can not understand what I am missing here.


Solution

  • The aspect needs to be created by Spring (in oder to apply the proxying).

    <bean id="simpleAspect" class="package-name.SimpleAspect"></bean>