【问题标题】:Why my service is autowired to a Proxy?为什么我的服务会自动连接到代理?
【发布时间】:2013-03-25 21:11:02
【问题描述】:

嗨,我有这门课要做测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/service.xml"})
public class Test {

    @Autowired private CommonService commonService;

在调试时,我在 CommonService 上获得了一个具有属性 h 的对象,它是一个 SdkDynamicAopProxy。

如何才能在我的属性 commonService 上获得一个 CommonServiceImp 对象?

公共服务

public interface CommonService {...}

CommonServiceImp

@Service("commonService")
@Transactional("transactionManager")
public class CommonServiceImp implements CommonService {
    @Autowired private CommonDaoJdbcImp commonDao; ...}

服务.xml

    <?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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/task
    http://www.springframework.org/schema/task/spring-task-3.0.xsd">

    <import resource="/bbb-dao.xml"/>

    <context:component-scan base-package="aaa.bbb.service"/>
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- <bean id="transactionManager" class="org.springframework.transaction.jta.WebSphereUowTransactionManager" /> -->
    <tx:annotation-driven />
<task:annotation-driven />

【问题讨论】:

  • 您的问题不清楚:如果您在代理上调用方法,它将由您的具体实现执行。您遇到了什么问题?

标签: java spring proxy aop autowired


【解决方案1】:

您的CommonServiceImp 类使用@Transactional 进行注释,并且您有一个使用&lt;tx:annotation-driven /&gt; 和事务管理器bean 进行事务管理的应用程序上下文。 Spring 使用代理来实现此行为并拦截您的所有方法调用并将它们与事务行为包装起来。这就是为什么您会看到 SdkDynamicAopProxy 而不是您班级的类型。

See the official documentation.

【讨论】:

  • 谢谢,我怎样才能修复我的代码,以便让我的 commonService 填充正确的 Object a CommonService?如果不可能,我如何管理代理对象以使用我的服务方法?提前致谢。
  • 您可以禁用事务管理,但我怀疑您是否想要这样做。代理最终会调用你的方法(这就是这种代理的目的),但只有在它调用自己的方法之后。
  • 我可以使用什么类来实例化这个代理对象?它是 Spring 类还是 java 类?。
  • Spring 为您服务。如果它需要代理一个类,它使用 cglib 库来实例化一个与你的类具有相同类型的代理。如果它需要代理一个接口,它使用 java 的代理 api。你真的无法控制这个。
猜你喜欢
  • 1970-01-01
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
  • 2011-10-11
  • 2019-05-17
  • 1970-01-01
  • 1970-01-01
  • 2020-10-14
相关资源
最近更新 更多