gpt4 book ai didi

spring - JavaConfig : Replacing aop:advisor and tx:advice

转载 作者:IT老高 更新时间:2023-10-28 13:46:59 33 4
gpt4 key购买 nike

我想知道是否可以将这段 xml 配置映射到 Spring JavaConfig:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
default-autowire="byName">

<aop:config>
<aop:pointcut id="serviceAnnotatedClass" expression="@within(org.springframework.stereotype.Service)" />
<aop:advisor id="managerTx" advice-ref="txAdvice" pointcut-ref="serviceAnnotatedClass" order="20" />
</aop:config>

<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="load*" read-only="true" />
<tx:method name="is*" read-only="true" />
<tx:method name="ownTransaction*" propagation="REQUIRES_NEW" rollback-for="Exception" />
<tx:method name="*" rollback-for="Exception" />
</tx:attributes>
</tx:advice>

</beans>

到目前为止,我想出了如何用

替换 aop:pointcut
<aop:advisor id="managerTx" advice-ref="txAdvice" 
pointcut="com.myapp.configuration.AspectConfig.serviceAnnotatedClass()" order="20"/>

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class AspectConfig
{

@Pointcut("@within(org.springframework.stereotype.Service)")
public void serviceAnnotatedClass() {}
}

任何提示如何替换其余部分?

最佳答案

如果你根本不想使用任何xml,那么你可以为方面创建一个单独的Java配置类

@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
}

并在您的主 AppConfig 类中导入上述配置类

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

现在创建你的方面 bean

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");
}

}

您可以使用切入点和如上所示的通知注释。

关于spring - JavaConfig : Replacing aop:advisor and tx:advice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14068525/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com