尝试在Spring应用程序中同时使用AspectJ和@Configurable。
@Component注释,那么AspectJ包装器可以工作并包装所有目标方法,而@Autowired注释会导致注入依赖项。但是,不能使用new关键字在运行时实例化该类并注入依赖项。@Configurable bean的AspectJ类,所有依赖项都会正确地注入到new上,但是没有一个方法是通过AspectJ代理的。,我怎么做到这两件事?
这是我的密码。配置:
@Configuration
@ComponentScan(basePackages="com.example")
@EnableSpringConfigured
@EnableAspectJAutoProxy
@EnableLoadTimeWeaving
public class TestCoreConfig {
@Bean
public SecurityAspect generateSecurityAspect(){
return new SecurityAspect();
}
@Bean
public SampleSecuredClass createSampleClass(){
return new SampleSecuredClass();
}
}方面:
@Aspect
public class SecurityAspect {
@Pointcut("execution(public * *(..))")
public void publicMethod() {}
@Around("publicMethod()")
public boolean test (ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("Here!");
joinPoint.proceed();
return true;
}
}SampleClass:
//@Configurable
@Component
public class SampleSecuredClass {
@Autowired
public SecurityService securityService;
public boolean hasSecurityService(){
return securityService != null;
}
public boolean returnFalse(){
return false;
}
}单元测试:
@ContextConfiguration(classes={TestCoreConfig.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class SecurityAspectComponentTest {
@Autowired
private SampleSecuredClass sampleSecuredClass;
@Test
public void testSecurityRoles(){
//SampleSecuredClass sampleSecuredClass = new SampleSecuredClass();
assertTrue("We need to ensure the the @Configurable annotation injected the services correctly", sampleSecuredClass.hasSecurityService());
assertTrue("We need to ensure the the method has been overwritten", sampleSecuredClass.returnFalse());
}
}TestCoreConfig中的bean,并在测试中使用new创建了一个SampleSecuredClass实例,并将其注释更改为@Configurable,那么服务就会被注入,但是方面不会被应用。SampleSecuredClass注入到bean中),那么方面可以工作,服务也会被注入,但是所有对象都必须在框架启动时创建。我想使用@Configurable注释。@Configurable注释和方面,那么我会得到一个illegal type in constant pool错误,并且上下文不会启动。其他信息。
发布于 2015-10-21 08:06:27
这似乎是一次深入文档的潜水活动,等待发生:)
首先,我将为org.springframework启用调试日志记录,因为这肯定会为Spring做什么和什么时候提供一些有意义的洞察.
话虽如此,我相信您的问题就在春天的生命周期的迷雾中,所以我会仔细地检查文档,特别是周围的文档。
depends-on="org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect"@Configurable(preConstruction=true)的笔记如果希望在构造函数体执行之前注入依赖项
@Configurable(autowire=Autowire.BY_NAME,dependencyCheck=true)最后,可以使用dependencyCheck属性启用Spring依赖项检查新创建和配置的对象中的对象引用。
仔细阅读文档,看看这些点击是否和如何应用,请让我们知道您找到的解决方案。它绝对应该是一个非常有趣的读物。
https://stackoverflow.com/questions/32925488
复制相似问题