I'm doing my fist steps with Springs AOP and wanted to start with a simple logging advice. My project is a multi module maven project with the following structure:
parentProject
|__aop
|__data
|__web
The web module has a user service class in the package de.my.awsome.project.web.service with a saveNewUser Method:
@Service
public class UserService {
...
public MdUser saveNewUser(UserModel user) {
MdUser newUser = this.save(user);
createGroupMembership(user, newUser);
return newUser;
}
}
The method works as expected so don't bother with details about that.
What I've done now is to create the following class in the aop module:
@Component
@Aspect
public class LoggingAspect {
Logger logger = Logger.getLogger(getClass());
@Before("execution(public * de.my.awsome.project.web.service.UserService.saveNewUser(..))")
public void newUserLog(JoinPoint joinpoint) {
logger.info(joinpoint.getSignature() + " with user " + joinpoint.getArgs()[0]);
}
}
I added a dependency for the web module in the pom of the aop module:
<dependency>
<groupId>de.my.awsome.project</groupId>
<artifactId>web</artifactId>
<version>${project.version}</version>
</dependency>
I even wrote a ConfigurationClasse even though I thought this would not be necessary with SpringBoot:
@Configuration
@ComponentScan(basePackages="de.fraport.bvd.mobisl.aop")
public class AspectsConfig {
}
The expected result is a log-message like "saveNewUser with user xyz". But the logging method is never called. What have I missed to do?
答案 0 :(得分:0)
@Configuration - Indicates that this file contains Spring Bean Configuration for an Aspect.
Replace @Component with @Configuration for LoggingAspect.
答案 1 :(得分:0)
好吧,@ sankar发表的答案也不起作用,但我自己找到了解决方法。
我必须在Web模块pom中向我的aop模块添加依赖项,反之亦然。然后,我将AspectsConfig的Import添加到Web模块SpringBootApplication类中,并且可以正常工作。
@SpringBootApplication
@Import(value= {JPAConfig.class, AspectsConfig.class})
@EnableAspectJAutoProxy
public class WebApplication {
@Autowired
private JPAConfig config;
@Autowired
private AspectsConfig aspectConfig;
public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
}
答案 2 :(得分:0)
以下步骤对我有用-如果有人在寻找解决方案,请参见下文
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
@Aspect
@Component
public class SampleAspect {
@After("execution(* de.my.awsome.project.testMethod())")
public void logAuditActivity(JoinPoint jp) {
System.out.println("TESTING ****************");
System.out.println("The method is called");
}
<dependency>
<groupId>de.my.awsome.project</groupId>
<artifactId>aop</artifactId>
</dependency>
@ComponentScan(basePackages = {"de.my.awsome.project", "de.my.awsome.aop" }