通過 <constructor-arg> 指定索引、類型、值。適用於強依賴、不可變對象。
<bean id="user1" class="cn.happy.entity.User">
<constructor-arg index="0" type="java.lang.String" value="LXL"/>
<constructor-arg index="1" type="java.lang.String" value="12"/>
</bean>
簡化 XML,屬性直接作為 XML 屬性。需引入 xmlns:p="https://www.springframework.org/schema/p"。
<bean id="user2" class="cn.happy.entity.User" p:name="你的肉" p:age="1" p:eamil="niderou@123.com"/>
實體類包含 List、Set、Map、Properties:
<!-- List -->
<property name="list">
<list><value>值1</value><value>值2</value></list>
</property>
<!-- Set -->
<property name="set">
<set><value>jd</value><value>tb</value></set>
</property>
<!-- Map -->
<property name="map">
<map>
<entry key="football" value="足球"/>
<entry key="basketball" value="籃球"/>
</map>
</property>
<!-- Properties -->
<property name="props">
<props>
<prop key="ndr">你的肉</prop>
<prop key="ndc">你的菜</prop>
</props>
</property>
Subject 定義契約。SubjectText 實現業務邏輯。ProxySubject 實現同一接口,持有真實對象引用,在調用前後添加增強邏輯。public class ProxySubject implements Subject {
private Subject subject;
public String quest() {
System.out.println("代理增強");
return subject.quest();
}
}
Proxy.newProxyInstance(ClassLoader, Class[], InvocationHandler)。InvocationHandler.invoke(proxy, method, args) 統一攔截所有方法調用。Subject proxy = (Subject) Proxy.newProxyInstance(
sub.getClass().getClassLoader(),
sub.getClass().getInterfaces(),
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("增強代碼");
return method.invoke(sub, args);
}
}
);
Spring AOP 底層正是基於動態代理(JDK Proxy 用於接口,CGLIB 用於類)。配置文件中引入 aop 命名空間,即可聲明式定義切面、切點、通知,實現事務、日誌、權限等橫切關注點分離。
