有条件地创建一个方面的方法是什么?我想要的是有条件地使用Spring扩展类:
@Aspect
public class Test1Aspect {
@DeclareParents(value="com.test.testClass",defaultImpl=Test1Impl.class)
public ITest iTest;
}
@Aspect
public class Test2Aspect {
@DeclareParents(value="com.test.testClass",defaultImpl=Test2Impl.class)
public ITest iTest;
}因此,testClass根据我设置该选项的属性文件扩展Test1Impl或Test2Impl,它可能吗?如何排除被调用的方面,我尝试使用aspectj plugin,但它并不排除我的方面:
pom.xml
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.5</version>
<configuration>
<sources>
<source>
<basedir>src/main/java</basedir>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</source>
</sources>
</configuration>
<executions>
<execution>
<goals>
<!-- use this goal to weave all your main classes -->
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>编辑
我删除了aspectj plugin,只使用Spring,下面是配置和测试方面:
Aplication.java
@Configuration
@ComponentScan(basePackages= {
"demo"
//"demo.aspect"
})
@EnableAutoConfiguration(exclude=AopAutoConfiguration.class)
//@EnableLoadTimeWeaving(aspectjWeaving=AspectJWeaving.ENABLED)
@EnableAspectJAutoProxy
public class Application {
public static final Logger LOGGER = LogManager.getLogger(Application.class);
@Bean
public testService testService() {
return new testService();
}
@Bean
@Conditional(TestCondition.class) //CLASS THAT ONLY RETURNS TRUE OR FALSE
public TestAspect testAspect() {
LOGGER.info("TEST ASPECT BEAN");
TestAspect aspect = Aspects.aspectOf(TestAspect.class);
return aspect;
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}TestAspect
//@Component
//@Profile("asdasd")
//@Configurable
//@Configuration
@Aspect
public class TestAspect{
public static final Logger LOGGER = LogManager.getLogger(TestAspect.class);
@Autowired
private testService testService;
public TestAspect() {
LOGGER.info("TEST ASPECT INITIALIZED");
}
@Around("execution(* demo.testControllerEX.test(*))")
public String prevent(ProceedingJoinPoint point) throws Throwable{
LOGGER.info("ASPECT AROUND " + testService); // ALWAYS CALLED NO MATTER IF THE CONDITION IS FALSE, THE ONLY DIFFERENCE IS THAT testService IS NULL WHEN THE CONDITION IS FALSE.
String result = (String)point.proceed();
return result;
}
/*@DeclareParents(value="(demo.testControllerEX)",defaultImpl=TestControllersImpl.class)
private ITestControllerEX itestControllerEX;*/
}发布于 2014-08-21 14:55:49
最后,我找到了解决方案,主要问题是,在我的Eclipse中,我在Spring的选项菜单(右键单击项目)中启用了方面工具,并且在Spring之前以某种方式使用传统的Aspectj编译了我的方面,所以这就解释了为什么无论我在方面上使用哪个条件都总是被应用。
因此,解决方案是不启用Spring工具。或者,如果启用了,请右击项目AspectJ Tools ->删除AspectJ功能。
发布于 2014-08-20 21:26:03
您可以在xml定义文件中使用@Conditional注释或使用PropertySourcesPlaceholderConfigurer。
例如,对于xml
test.aspect = org.example.Test1Aspect
<context:property-placeholder location="configuration.properties" />
<bean id="testAspect" class="${test.aspect}" />您不需要Spring的maven aspectj插件。
https://stackoverflow.com/questions/25410144
复制相似问题