春季AOP无需@EnableAspectJAutoProxy即可工作?
2022-09-01 13:04:45
我正在学习Spring(目前是它的AOP框架)。尽管我读过的所有源代码都说要启用AOP,需要使用注释(或其XML对应物),但我的代码似乎可以使用注释注释。这是因为我使用的是龙目岛还是Spring Boot(v. 1.5.9.RELEASE,依赖于Spring v. 4.3.13.RELEASE)?@EnableAspectJAutoProxy
最小示例如下:
build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
group = 'lukeg'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter')
compileOnly('org.projectlombok:lombok')
compile("org.aspectj:aspectjweaver:1.8.11")
testCompile('org.springframework.boot:spring-boot-starter-test')
}
应用程序配置.java(请注意,AOP 批注已注释掉)
package lukeg;
import org.springframework.context.annotation.*;
@Configuration
@ComponentScan
//@EnableAspectJAutoProxy
public class ApplicationConfiguration {
@Bean
TestComponent testComponent() {
return new TestComponent();
}
}
学习应用.java
package lukeg;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@SpringBootApplication
public class LearnApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(LearnApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
TestComponent testComponent = context.getBean(TestComponent.class);
System.out.println(""+testComponent);
}
}
伐木工.java
package lukeg;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class LoggerHogger {
@Pointcut("execution(* lukeg*.*.toString(..))")
public void logToString() {}
@Before("logToString()")
public void beforeToString () {
System.out.println("Before toString");
}
}
测试组件.java
package lukeg;
import lombok.Data;
@Data
public class TestComponent {
}