# 6.5. 简洁的代理定义

尤其是在定义事务代理时，您最终可能会得到许多类似的代理定义。使用父 bean 和子 bean 定义以及内部 bean 定义，可以产生更清晰和更简洁的代理定义。

首先，我们为代理创建一个父、模板、bean定义，如下：

```xml
<bean id="txProxyTemplate" abstract="true"
        class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    <property name="transactionManager" ref="transactionManager"/>
    <property name="transactionAttributes">
        <props>
            <prop key="*">PROPAGATION_REQUIRED</prop>
        </props>
    </property>
</bean>
```

这本身永远不会被实例化，因此它实际上可能是不完整的。然后，需要创建的每个代理都是一个子 bean 定义，它将代理的目标包装为内部 bean 定义，因为目标永远不会单独使用。以下示例显示了这样一个子 bean：

```xml
<bean id="myService" parent="txProxyTemplate">
    <property name="target">
        <bean class="org.springframework.samples.MyServiceImpl">
        </bean>
    </property>
</bean>
```

您可以覆盖父模板中的属性。在以下示例中，我们覆盖了事务传播设置：

```xml
<bean id="mySpecialService" parent="txProxyTemplate">
    <property name="target">
        <bean class="org.springframework.samples.MySpecialServiceImpl">
        </bean>
    </property>
    <property name="transactionAttributes">
        <props>
            <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
            <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
            <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>
            <prop key="store*">PROPAGATION_REQUIRED</prop>
        </props>
    </property>
</bean>
```

请注意，在父 bean 示例中，我们通过将`abstract`属性设置为`true` 明确地将父 bean 定义标记为抽象， [如前所述](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-child-bean-definitions)，因此它实际上可能不会被实例化。默认情况下，应用程序上下文（但不是简单的 bean 工厂）预先实例化所有单例。因此，重要的是（至少对于单例 bean），如果您有一个（父）bean 定义打算仅用作模板，并且此定义指定了一个类，则必须确保将`abstract` 属性设置为`true`. 否则，应用程序上下文实际上会尝试预先实例化它。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://doc.shiker.tech/spring-he-xin-gong-neng/6.-spring-aop-api/6.5.-jian-jie-de-dai-li-ding-yi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
