JavaConfig: Replacing aop:advisor and tx:advice

后端 未结 2 2075
野趣味
野趣味 2021-01-31 00:58

I\'m wondering if I can map this piece of xml-configuration to Spring JavaConfig:




        
2条回答
  •  广开言路
    2021-01-31 01:18

    If you don't want to use any xml at all, then you can create a separate Java configuration class for aspects

    @Configuration
    @EnableAspectJAutoProxy
    @ComponentScan(basePackages = "com.myAspects")
    public class AspectConfig {
        //Here you can define Aspect beans or just use @ComponentScan (as above)
        //to scan the @Aspect annotation in com.myAspects package
    }
    

    And import above configuration class in your main AppConfig class

    @Configuration
    @EnableWebMvc
    @Import({ AspectConfig.class })
    @ComponentScan(basePackages = { "pkg1", "pkg2", "pkg3" })
    public class AppConfiguration extends WebMvcConfigurationSupport {
        //Other configuration beans or methods
    }
    

    Now create your aspect beans

    import com.myAspects;
    @Component
    @Aspect
    public class LoggingAspect {
    
        @Before("execution(* com.service.*.*(..))")
        public void logBefore(){
            System.out.println("before advice called");
        } 
    
        @After("execution(* com.service.*.*(..))")
        public void logAfter(){
            System.out.println("after advice called");
        } 
    
    }
    

    You can use pointcut along with advice annotation as shown above.

提交回复
热议问题