# 3.4.2　在 XML 中声明作用域代理

如果你需要使用 XML 来声明会话或请求作用域的 bean，那么就不能使用 @Scope 注解及其 proxyMode 属性了。元素的 scope 属性能够设置 bean 的作用域，但是该怎样指定代理模式呢？

要设置代理模式，我们需要使用 Spring aop 命名空间的一个新元素：

```markup
<bean id="cart" class="com.myapp.ShoppingCart" scope="session">
  <aop:scoped-proxy />
</bean>
```

`<aop:scoped-proxy>` 是与 @Scope 注解的 proxyMode 属性功能相同的 Spring XML 配置元素。它会告诉 Spring 为 bean 创建一个作用域代理。默认情况下，它会使用 CGLib 创建目标类的代理。但是我们也可以将 proxy-target-class 属性设置为 false，进而要求它生成基于接口的代理：

```markup
<bean id="cart" class="com.myapp.ShoppingCart" scope="session">
  <aop:scoped-proxy proxy-target-class="false" />
</bean>
```

为了使用 `<aop:scoped-proxy>` 元素，我们必须在 XML 配置中声明 Spring 的 aop 命名空间：

{% code title="" %}

```markup
<?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"
  xsi:schemaLocation="
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/beans/spring-aop.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd" >
    ...
</beans>
```

{% endcode %}

在第 4 章中，当我们使用 Spring 和面向切面编程的时候，会讨论 Spring aop 命名空间的更多知识。不过，在结束本章的内容之前，我们来看 一下 Spring 高级配置的另外一个可选方案：Spring 表达式语言（Spring Expression Language）。


---

# 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://potoyang.gitbook.io/spring-in-action-v4/di-3-zhang-gao-ji-zhuang-pei/untitled-2/untitled-1.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.
