当前位置: 首页 > 知识库问答 >
问题:

由于proxy-target-class=“true”和,spring无法自动生成

南门烈
2023-03-14

我有以下spring配置:

<context:annotation-config />
<security:global-method-security jsr250-annotations="enabled"  pre-post-annotations="enabled" proxy-target-class="true" />

<tx:annotation-driven  />

<aop:aspectj-autoproxy />

<context:component-scan base-package="com.web,com.security" />

我在global-method-security中启用了proxy-target-class,因为我希望在控制器中使用@preauthorize注释(我知道spring团队不鼓励这样做),并且在保存对象时使用aop aspectJ作为服务中的“拦截器”。

这似乎是因为启用了global-method-security中的代理配置,并且默认的aop,aspectj正在使用代理实现。它未能自动连接所有控制器中的bean。代理代理?

控制器

@RequestMapping(value = "add")
@PreAuthorize("@securityPermission.validatePermission()")
public String add(Model model) {
   //codes
}

带有@Aspect注释的我的服务类

@SuppressWarnings("serial")
@Aspect
@Service
public class InterceptorServiceImpl extends BaseServiceImplementation implements InterceptorService {
@Autowired
    private LogRepository logRepository;

@Around("execution(* com.repository.CardRequestRepository.save(..))")
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class,timeout = 30)
   public Object checkProcess(ProceedingJoinPoint joinPoint) throws Throwable{
   LOGGER.info("SERVICE : START Process checking Interceptor");

}   

错误日志:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'approvalActivityController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.csl.cms.service.ApprovalActivityService com.csl.cms.web.ApprovalActivityController.approvalActivityService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'approvalActivityServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.csl.cms.repository.CardRequestRepository com.csl.cms.service.serviceimplementasi.ApprovalActivityServiceImpl.cardRequestRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cardRequestRepository': Post-processing of the FactoryBean's object failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.sun.proxy.$Proxy572]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy572
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:472)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:388)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:293)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.manager.ManagerServlet.start(ManagerServlet.java:1256)
at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:376)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:581)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)


Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.sun.proxy.$Proxy572]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy572
at org.springframework.aop.framework.Cglib2AopProxy.getProxy(Cglib2AopProxy.java:213)
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:112)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:477)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:362)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:407)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.postProcessObjectFromFactoryBean(AbstractAutowireCapableBeanFactory.java:1598)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:162)
... 65 more
Caused by: java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy572
    at net.sf.cglib.proxy.Enhancer.generateClass(Enhancer.java:446)
    at net.sf.cglib.transform.TransformingClassGenerator.generateClass(TransformingClassGenerator.java:33)
    at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
    at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
    at net.sf.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
    at net.sf.cglib.proxy.Enhancer.create(Enhancer.java:285)
    at org.springframework.aop.framework.Cglib2AopProxy.getProxy(Cglib2AopProxy.java:201)
    ... 72 more

存储库类

public interface CardRequestRepository extends JpaRepository<CardRequest, Long>, CardRequestRepositoryCustom {
public List<CardRequest> findByCardholderId(Long cardholderId);

@Query("Select cr FROM CardRequest cr "
        + "LEFT JOIN FETCH cr.cardholder ch "
        + "LEFT JOIN FETCH ch.identityDocument "
        + "LEFT JOIN FETCH cr.program p "
        + "WHERE cr.id = :id")
public CardRequest findOneFetching(@Param("id") Long cardholderId);

}

public interface CardRequestRepositoryCustom {

    public List<CardRequest> findCardRequestWithDatatablesCriterias(DatatablesCriterias criterias);
.....

服务impl类

@SuppressWarnings("serial")
@Service
public class ApprovalActivityServiceImpl extends BaseServiceImplementasi implements ApprovalActivityService {

    @Autowired
    private ApprovalActivityRepository approvalActivityRepository;
    ...
    @Autowired
    private MessageSource messageSource;

    @Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
    public ApprovalActivity findOne(Long id) {
        LOGGER.info("SERVICE : ApprovalActivity findOne id =" + id);
        return approvalActivityRepository.findOne(id);
    }
}

baseserviceimpl类

public abstract class BaseServiceImplementasi
  implements Serializable
{
  protected transient Logger LOGGER = Logger.getLogger(getClass());
}

同时使用aop:aspectj-autoproxy和enable proxy-target-class是否可能?或者有人有别的建议吗?:)

Autowire失败问题已解决

根据@m.deinum的建议,我解决了自己的自动操作问题,在以下文件中添加了proxy-target-class=“true”属性:

<tx:annotation-driven /> 
<cache:annotation-driven />
<aop:aspectj-autoproxy />

并且我用@aspect注释删除了类中的@service。

注意:在InterceptorServiceImpl中,我使用了@service,因为我希望@autowiring调用存储库/服务bean

发生的方面类问题:

这似乎是因为我删除了aspect类中的@Service注释,aop aspectj不知为什么没有执行,日志中也没有错误。

共有1个答案

越霖
2023-03-14

我解决了我的问题,这似乎是因为在我的repository类中使用了数据jpa(JpaRepository)。下面是我的xml配置:

<security:global-method-security jsr250-annotations="enabled" pre-post-annotations="enabled" proxy-target-class="true"/> //enabled proxy to use @preAuthorize in controller
<tx:annotation-driven />
<cache:annotation-driven />
<aop:aspectj-autoproxy />
<context:component-scan base-package="com.xxx.xxx.service.serviceimplementasi" />  
<jpa:repositories  base-package="com.csl.cms.repository" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager"  /> 

数据jpa配置:

<!--Spring Data JPA Configuration-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
        <property name="dataSource" ref="c3p0DataSource-1" />
        <property name="packagesToScan" value="com.xxx.xxx.entity"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="databasePlatform" value="${database.dialect}" /> 
                <property name="showSql" value="true" />
                <property name="generateDdl" value="true" />
            </bean>
        </property>
    </bean>
    <bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />        
        <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
        </property>
    </bean>

存储库类:

public interface CardRequestRepository extends JpaRepository<CardRequest, Long>, CardRequestRepositoryCustom {
    public List<CardRequest> findByCardholderId(Long cardholderId);

在CardRequestRepositoryCustom类中,使用entityManager创建一个自定义save方法,这样它就不会依赖于JPararePository类。

public class CardRequestRepositoryImpl implements CardRequestRepositoryCustom {

    @PersistenceContext
    private EntityManager em;

 @Override
    public CardRequest customSave(CardRequest cardRequest) {
       em.persist(cardRequest);
       return cardRequest;
    }

我还在aspect类中更改了point cut,使用repository自定义类:

@SuppressWarnings("serial")
@Aspect
@Component
public class ApprovalInterceptorServiceImpl extends BaseServiceImplementasi implements ApprovalInterceptorService {

    @Autowired
    private LifecycleLogRepository lifecycleLogRepository;
    @Autowired
    private ApprovalDefinitionRepository approvalDefinitionRepository;
    @Around("execution(* com.xxx.xxx.repository.repositoryimplementasi.CardRequestRepositoryImpl.customSave(..))")
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class,timeout = 30)
    public CardRequest checkApprovalProcess(ProceedingJoinPoint joinPoint) throws Throwable{
    LOGGER.info("SERVICE : START Approval Process checking Interceptor");
                System.out.println("SERVICE : START Approval Process checking Interceptor");

                Object messageParam[] = new Object[1];
        Object[] objs = joinPoint.getArgs();
        CardRequest cardRequest = (CardRequest) objs[0];

....

在aop方面类中,使用@Component自动生成服务bean并且不使用JPararePository扩展存储库类,而是使用/创建一个自定义存储库类和entityManager来保存对象。有了这个配置和代码,我的代理类问题就解决了。

如果我在aspect类中应用了@component、@autowired并使用JPararePository,那么存储库bean类将无法自动生成。仍然不知道为什么会发生。

 类似资料:
  • target.browser() returns: <Browser> 获取目标所属的浏览器。 target.browserContext() returns: <BrowserContext> 目标所属的浏览器上下文。 target.createCDPSession() returns: <Promise<CDPSession>> 创建一个 Chrome Devtools 协议会话至目标。 ta

  • 我使用的是Spring Boot1.4、Spock和Spring-boot-starter-security。这是我的相关年级档案: 我还将其添加到我的application-test.properties文件中: 我的基测试类将启动一个嵌入式Tomcat实例并使所有endpoint可用,并且有一个获取JWT的方法: 当我尝试运行示例测试时: 我得到以下信息:

  • 问题内容: 我已经在网上搜索过,却找不到与我的问题相似的内容。 我创建了一个空的C ++项目,并添加了带有返回的main.cpp,但无法构建它。这是我收到的消息: VS2012中是否可以在哪里指定可以在哪里找到此可执行文件?我已经安装了Windows 7 SDK,并且在以下位置具有此可执行文件: 我来自Code :: Blocks,使用mingw-gcc时没有任何麻烦,但是最近我一直需要使用VS来

  • 我有两个简介,dev和Prod。我的文件如下所示 我的理解是: 属性告诉Spring,如果没有指定配置文件,则使用prod配置文件 Spring将视为“文件分隔符”,如果参数的计算结果为true,则重新计算每组属性并覆盖以前的值 鉴于这种理解,我希望Spring首先解析“默认”属性,了解默认激活的配置文件应该是prod。然后它将解析prod属性。由于“prod”是一个活动配置文件(唯一的活动配置文

  • 在尝试创建具有自动生成ID的表时,我遇到了一个异常: commandAcceptanceException:“执行DDL时出错”create table seat(id bigint not null,description varchar(255),num integer not null,PROCY decimal(19,2),row char(255)not null,primary key

  • 我一直在尝试启动NiFi,但每次我这样做,我都得到以下错误: