视频地址:http://www.imooc.com/learn/196
一、spring注入
- 设值注入
<bean id="injectionService" class="com.twx.ioc.injection.service.InjectionServiceImpl">
<property name="injectionDao" ref="injectionDAO"></property>
</bean>
<bean id="injectionDAO" class="com.twx.ioc.injection.dao.InjectionDAOImpl"></bean>
- 构造注入
<bean id="injectionService" class="com.twx.ioc.injection.service.InjectionServiceImpl">
<constructor-arg name="injectionDao" ref="injectionDAO"></constructor-arg>
</bean>
<bean id="injectionDAO" class="com.twx.ioc.injection.dao.InjectionDAOImpl"></bean>
二、Bean的作用域
多例:prototype
<bean id="beanScope" class="com.twx.bean.BeanScope" scope="prototype"></bean>
测试代码:
@Test
public void testSay() {
BeanScope beanScope = super.getBean("beanScope");
beanScope.say();
BeanScope beanScope2 = super.getBean("beanScope");
beanScope2.say();
}
@Test
public void testSay2() {
BeanScope beanScope = super.getBean("beanScope");
beanScope.say();
}
三、Aware接口
public class TwxApplicationContext implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("twxApplicationContext: "+applicationContext.getBean("twxApplicationContext").hashCode());
}
}
<!-- <bean id="twxApplicationContext" class="com.twx.aware.TwxApplicationContext"></bean> -->
<bean id="twxBeanName" class="com.twx.aware.TwxBeanName"></bean>
测试类:
public TestAware() {
super("classpath*:spring-aware.xml");
}
/*@Test
public void testTwxApplicationContext(){
System.out.println("testTwxApplicationContext: "+super.getBean("twxApplicationContext").hashCode());
}
*/
@Test
public void testTwxBeanName(){
System.out.println("testTwxBeanName: "+super.getBean("twxBeanName"));
}
四、Bean的自动装配
4-1、byName:
dao:
package com.twx.autowiring;
public class AutoWiringDAO {
public void say(String word) {
System.out.println("AutoWiringDAO : " + word);
}
}
service
package com.twx.autowiring;
public class AutoWiringService {
private AutoWiringDAO autoWiringDAO;
/*public AutoWiringService(AutoWiringDAO autoWiringDAO) {
System.out.println("AutoWiringService");
this.autoWiringDAO = autoWiringDAO;
}*/
public void setAutoWiringDAO(AutoWiringDAO autoWiringDAO) {
System.out.println("setAutoWiringDAO");
this.autoWiringDAO = autoWiringDAO;
}
public void say(String word) {
this.autoWiringDAO.say(word);
}
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
default-autowire="byName">
<bean id="autoWiringService" class="com.twx.autowiring.AutoWiringService" ></bean>
<bean id="autoWiringDAO" class="com.twx.autowiring.AutoWiringDAO" ></bean>
</beans>
test
package com.twx.autowiring;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import com.twx.test.base.UnitTestBase;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestAutoWiring extends UnitTestBase {
public TestAutoWiring() {
super("classpath:spring-autowiring.xml");
}
@Test
public void testSay() {
AutoWiringService service = super.getBean("autoWiringService");
service.say(" this is a test");
}
}
4-2、byType
把default-autowire=”byName” 改为 default-autowire=”byType”
其他同上
4-3、constructor
service
public class AutoWiringService {
private AutoWiringDAO autoWiringDAO;
public AutoWiringService(AutoWiringDAO autoWiringDAO) {
System.out.println("AutoWiringService");
this.autoWiringDAO = autoWiringDAO;
}
public void setAutoWiringDAO(AutoWiringDAO autoWiringDAO) {
System.out.println("setAutoWiringDAO");
this.autoWiringDAO = autoWiringDAO;
}
public void say(String word) {
this.autoWiringDAO.say(word);
}
}
xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
default-autowire="constructor">
<bean id="autoWiringService" class="com.twx.autowiring.AutoWiringService" ></bean>
<bean id="autoWiringDAO" class="com.twx.autowiring.AutoWiringDAO" ></bean>
</beans>
五、Bean的注解
@Component
@Repository—–用于注解DAO层
@Service———用于注解服务层
@Controller—–用于注解控制层
类的自动检测以及注册
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" >
<context:component-scan base-package="com.twx.beanannotation"></context:component-scan>
</beans>
实体类:
package com.twx.beanannotation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
//@Component("bean")
@Scope("prototype")
@Component
public class BeanAnnotation {
public void say(String arg) {
System.out.println("BeanAnnotation : " + arg);
}
public void myHashCode() {
System.out.println("BeanAnnotation : " + this.hashCode());
}
}
六、Autowired
6-1、成员变量
DAO:
package com.twx.beanannotation.injection.dao;
import org.springframework.stereotype.Repository;
@Repository
public class InjectionDAOImpl implements InjectionDAO {
public void save(String arg) {
//模拟数据库保存操作
System.out.println("保存数据:" + arg);
}
}
Service:
package com.twx.beanannotation.injection.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.twx.beanannotation.injection.dao.InjectionDAO;
@Service
public class InjectionServiceImpl implements InjectionService {
@Autowired
private InjectionDAO injectionDAO;
/*@Autowired
public InjectionServiceImpl(InjectionDAO injectionDAO) {
this.injectionDAO = injectionDAO;
}*/
// @Autowired
public void setInjectionDAO(InjectionDAO injectionDAO) {
this.injectionDAO = injectionDAO;
}
public void save(String arg) {
//模拟业务操作
System.out.println("Service接收参数:" + arg);
arg = arg + ":" + this.hashCode();
injectionDAO.save(arg);
}
}
测试类:
package com.twx.beanannotation;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import com.twx.beanannotation.injection.service.InjectionService;
import com.twx.test.base.UnitTestBase;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestInjection extends UnitTestBase {
public TestInjection() {
super("classpath:spring-beanannotation.xml");
}
@Test
public void testAutowired() {
InjectionService service = super.getBean("injectionServiceImpl");
service.save("This is autowired.");
}
/*@Test
public void testMultiBean() {
BeanInvoker invoker = super.getBean("beanInvoker");
invoker.say();
}*/
}
6-2、构造器
service
package com.twx.beanannotation.injection.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.twx.beanannotation.injection.dao.InjectionDAO;
@Service
public class InjectionServiceImpl implements InjectionService {
// @Autowired
private InjectionDAO injectionDAO;
@Autowired
public InjectionServiceImpl(InjectionDAO injectionDAO) {
this.injectionDAO = injectionDAO;
}
// @Autowired
public void setInjectionDAO(InjectionDAO injectionDAO) {
this.injectionDAO = injectionDAO;
}
public void save(String arg) {
//模拟业务操作
System.out.println("Service接收参数:" + arg);
arg = arg + ":" + this.hashCode();
injectionDAO.save(arg);
}
}
6-3、使用Qualifier来缩写注解的范围
七、基于Java的容器注解说明(一)
接口:
package com.twx.beanannotation.javabased;
public interface Store<T> {
}
接口实现类:
package com.twx.beanannotation.javabased;
public class StringStore implements Store<String> {
public void init() {
System.out.println("This is init.");
}
public void destroy() {
System.out.println("This is destroy.");
}
}
配置类:
package com.twx.beanannotation.javabased;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
public class StoreConfig {
@Bean(name = "stringStoreTest",initMethod="init",destroyMethod="destroy")
public Store stringStoreTest() {
return new StringStore();
}
}
测试类:
package com.twx.beanannotation;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import com.twx.beanannotation.javabased.Store;
import com.twx.test.base.UnitTestBase;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestJavabased extends UnitTestBase {
public TestJavabased() {
super("classpath*:spring-beanannotation.xml");
}
@Test
public void test() {
Store store = super.getBean("stringStoreTest");
System.out.println(store.getClass().getName());
}
}
八、基于Java的容器注解说明(二)
@ImportResource和@Value进行资源文件读取
MyDriver:
package com.twx.beanannotation.javabased;
public class MyDriverManager {
public MyDriverManager(String url, String userName, String password) {
System.out.println("url : " + url);
System.out.println("userName: " + userName);
System.out.println("password: " + password);
}
}
配置:
package com.twx.beanannotation.javabased;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Scope;
@Configuration
@ImportResource("classpath:config.xml")
public class StoreConfig {
@Value("${url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${password}")
private String password;
@Bean
public MyDriverManager myDriverManager() {
return new MyDriverManager(url, username, password);
}
}
资源文件:config.xml 和config.properties
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" >
<context:property-placeholder location="classpath:/config.properties"/>
</beans>
#Created by JInto - www.guh-software.de
#Sun Aug 10 16:25:57 CST 2014
jdbc.username=root
password=root
url=127.0.0.1
测试类:
package com.twx.beanannotation;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import com.twx.beanannotation.javabased.MyDriverManager;
import com.twx.beanannotation.javabased.Store;
import com.twx.test.base.UnitTestBase;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestJavabased extends UnitTestBase {
public TestJavabased() {
super("classpath*:spring-beanannotation.xml");
}
@Test
public void testMyDriverManager() {
MyDriverManager manager = super.getBean("myDriverManager");
System.out.println(manager.getClass().getName());
}
}
九、基于Java的容器注解说明(三)
@Bean和@Scope
配置类:
package com.twx.beanannotation.javabased;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class StoreConfig {
@Bean(name = "stringStore")
@Scope(value="prototype")
public Store stringStore() {
return new StringStore();
}
}
测试类:
package com.twx.beanannotation;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import com.twx.beanannotation.javabased.Store;
import com.twx.test.base.UnitTestBase;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestJavabased extends UnitTestBase {
public TestJavabased() {
super("classpath*:spring-beanannotation.xml");
}
@Test
public void testScope() {
Store store = super.getBean("stringStore");
System.out.println(store.hashCode());
store = super.getBean("stringStore");
System.out.println(store.hashCode());
}
}
十、基于Java的容器注解说明(四)
基于泛型的自动装配
配置:
package com.twx.beanannotation.javabased;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Scope;
@Configuration
public class StoreConfig {
@Autowired
private Store<String> s1;
@Autowired
private Store<Integer> s2;
@Bean
public StringStore stringStore() {
return new StringStore();
}
@Bean
public IntegerStore integerStore() {
return new IntegerStore();
}
@Bean(name = "stringStoreTest",initMethod="init",destroyMethod="destroy")
public Store stringStoreTest() {
System.out.println("s1:"+s1.getClass().getName());
System.out.println("s2:"+s2.getClass().getName());
return new StringStore();
}
}
测试:
package com.twx.beanannotation;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import com.twx.beanannotation.javabased.MyDriverManager;
import com.twx.beanannotation.javabased.Store;
import com.twx.beanannotation.javabased.StringStore;
import com.twx.test.base.UnitTestBase;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestJavabased extends UnitTestBase {
public TestJavabased() {
super("classpath*:spring-beanannotation.xml");
}
@Test
public void testG() {
StringStore store = super.getBean("stringStoreTest");
}
}
输出结果:
s1:com.twx.beanannotation.javabased.StringStore
s2:com.twx.beanannotation.javabased.IntegerStore
This is init.
This is destroy.
十一、 AOP应用(上)
spring-aop-schema-advice.xml:
一旦执行com.twx.aop.schema.advice.biz包下以Biz结尾的类的方法,就会自动切入执行com.twx.aop.schema.advice.MoocAspect中配置文件指定的方法。
<?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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<bean id="moocAspect" class="com.twx.aop.schema.advice.MoocAspect"></bean>
<bean id="aspectBiz" class="com.twx.aop.schema.advice.biz.AspectBiz"></bean>
<aop:config>
<aop:aspect id="moocAspectAOP" ref="moocAspect">
<aop:pointcut expression="execution(* com.twx.aop.schema.advice.biz.*Biz.*(..))" id="moocPiontcut"/>
<aop:before method="before" pointcut-ref="moocPiontcut"/>
<aop:after-returning method="afterReturning" pointcut-ref="moocPiontcut"/>
<aop:after-throwing method="afterThrowing" pointcut-ref="moocPiontcut"/>
<aop:after method="after" pointcut-ref="moocPiontcut"/>
</aop:aspect>
</aop:config>
</beans>
切面类:
package com.twx.aop.schema.advice;
public class MoocAspect {
public void before() {
System.out.println("MoocAspect before.");
}
public void afterReturning() {
System.out.println("MoocAspect afterReturning.");
}
public void afterThrowing() {
System.out.println("MoocAspect afterThrowing.");
}
public void after() {
System.out.println("MoocAspect after.");
}
}
业务逻辑类:
package com.twx.aop.schema.advice.biz;
public class AspectBiz {
public void biz() {
System.out.println("AspectBiz biz.");
// throw new RuntimeException();
}
}
测试类:
package com.twx.aop;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import com.twx.aop.schema.advice.biz.AspectBiz;
import com.twx.test.base.UnitTestBase;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestAOPSchemaAdvice extends UnitTestBase {
public TestAOPSchemaAdvice() {
super("classpath:spring-aop-schema-advice.xml");
}
@Test
public void testBiz() {
AspectBiz biz = super.getBean("aspectBiz");
biz.biz();
}
}
输出结果:
MoocAspect before.
AspectBiz biz.
MoocAspect afterReturning.
MoocAspect after.
十二、AOP应用(下)
12-1、around service
通知方法的第一个参数必须是ProceedingJoinPoint类型
- 在spring-aop-schema-advice.xml中添加:
<aop:around method="around" pointcut-ref="moocPiontcut"/>
- MoocAspect.java中添加:
public Object around(ProceedingJoinPoint pjp) {
Object obj = null;
try {
System.out.println("MoocAspect around 1.");
obj = pjp.proceed();
System.out.println("MoocAspect around 2.");
} catch (Throwable e) {
e.printStackTrace();
}
return obj;
}
- 输出结果:
MoocAspect before.
MoocAspect around 1.
AspectBiz biz.
MoocAspect around 2.
MoocAspect after.
MoocAspect afterReturning.
12-2、advice parameters
- 业务逻辑类AspectBiz.java:
package com.twx.aop.schema.advice.biz;
public class AspectBiz {
public void biz() {
System.out.println("AspectBiz biz.");
// throw new RuntimeException();
}
public void init(String bizName, int times) {
System.out.println("AspectBiz init : " + bizName + " " + times);
}
}
- 切面类MoocAspect .java:
package com.twx.aop.schema.advice;
import org.aspectj.lang.ProceedingJoinPoint;
public class MoocAspect {
public Object aroundInit(ProceedingJoinPoint pjp, String bizName, int times) {
System.out.println(bizName + " " + times);
Object obj = null;
try {
System.out.println("MoocAspect aroundInit 1.");
obj = pjp.proceed();
System.out.println("MoocAspect aroundInit 2.");
} catch (Throwable e) {
e.printStackTrace();
}
return obj;
}
}
- 配置文件:
<?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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<bean id="moocAspect" class="com.twx.aop.schema.advice.MoocAspect"></bean>
<bean id="aspectBiz" class="com.twx.aop.schema.advice.biz.AspectBiz"></bean>
<aop:config>
<aop:aspect id="moocAspectAOP" ref="moocAspect">
<aop:around method="aroundInit" pointcut="execution(* com.twx.aop.schema.advice.biz.AspectBiz.init(String, int))
and args(bizName, times)"/>
</aop:aspect>
</aop:config>
</beans>
- 测试方法:
@Test
public void testInit() {
AspectBiz biz = super.getBean("aspectBiz");
biz.init("moocService", 3);
}
- 输出结果:
moocService 3
MoocAspect aroundInit 1.
AspectBiz init : moocService 3
MoocAspect aroundInit 2.
十三、Introduction应用
允许一个切面声明一个实现指定接口的通知对象,并且提供了一个接口实现类来代替这个对象。
由<aop:aspect>
中的<aop:declare-parents>
声明该元素用于声明所匹配的类型一个新的parent。(很拗口啊),看实例吧。
- 创建接口Fit.java:
package com.twx.aop.schema.advice;
public interface Fit {
void filter();
}
- 接口实现类FitImpl.java:
package com.twx.aop.schema.advice;
public class FitImpl implements Fit {
@Override
public void filter() {
System.out.println("FitImpl filter.");
}
}
- 配置文件:
<?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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<bean id="moocAspect" class="com.twx.aop.schema.advice.MoocAspect"></bean>
<bean id="aspectBiz" class="com.twx.aop.schema.advice.biz.AspectBiz"></bean>
<aop:config>
<aop:aspect id="moocAspectAOP" ref="moocAspect">
<aop:around method="aroundInit" pointcut="execution(* com.twx.aop.schema.advice.biz.AspectBiz.init(String, int))
and args(bizName, times)"/>
<aop:declare-parents types-matching="com.twx.aop.schema.advice.biz.*(+)"
implement-interface="com.twx.aop.schema.advice.Fit"
default-impl="com.twx.aop.schema.advice.FitImpl"/>
</aop:aspect>
</aop:config>
</beans>
- 测试类:
@Test
public void testFit() {
Fit fit = (Fit)super.getBean("aspectBiz");
fit.filter();
}
- 测试结果:
FitImpl filter.
- 分析:
super.getBean(“aspectBiz”);本来获取到的是AspectBiz对象,但是在配置文件中的中指定了其默认的父类接口及其实现类,所以可以把AspectBiz对象强制转换为Fit对象。
十四、Advisor
- 创建业务逻辑类InvokeService .java:
package com.twx.aop.schema.advisors.service;
import org.springframework.dao.PessimisticLockingFailureException;
import org.springframework.stereotype.Service;
@Service
public class InvokeService {
public void invoke() {
System.out.println("InvokeService ......");
}
public void invokeException() {
throw new PessimisticLockingFailureException("");
}
}
- 创建切面类ConcurrentOperationExecutor .java:
package com.twx.aop.schema.advisors;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.core.Ordered;
import org.springframework.dao.PessimisticLockingFailureException;
public class ConcurrentOperationExecutor implements Ordered {
private static final int DEFAULT_MAX_RETRIES = 2;
private int maxRetries = DEFAULT_MAX_RETRIES;
private int order = 1;
public void setMaxRetries(int maxRetries) {
this.maxRetries = maxRetries;
}
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
int numAttempts = 0;
PessimisticLockingFailureException lockFailureException;
do {
numAttempts++;
System.out.println("Try times : " + numAttempts);
try {
return pjp.proceed();
} catch (PessimisticLockingFailureException ex) {
lockFailureException = ex;
}
} while (numAttempts <= this.maxRetries);
System.out.println("Try error : " + numAttempts);
throw lockFailureException;
}
}
- 创建配置文件spring-aop-schema-advisors.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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.twx.aop.schema"></context:component-scan>
<aop:config>
<aop:aspect id="concurrentOperationRetry" ref="concurrentOperationExecutor">
<aop:pointcut id="idempotentOperation"
expression="execution(* com.twx.aop.schema.advisors.service.*.*(..)) " />
<!-- expression="execution(* com.imooc.aop.schema.service.*.*(..)) and -->
<!-- @annotation(com.imooc.aop.schema.Idempotent)" /> -->
<aop:around pointcut-ref="idempotentOperation" method="doConcurrentOperation" />
</aop:aspect>
</aop:config>
<bean id="concurrentOperationExecutor" class="com.twx.aop.schema.advisors.ConcurrentOperationExecutor">
<property name="maxRetries" value="3" />
<property name="order" value="100" />
</bean>
</beans>
- 测试类:
package com.twx.aop;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import com.twx.aop.schema.advisors.service.InvokeService;
import com.twx.test.base.UnitTestBase;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestAOPSchemaAdvisors extends UnitTestBase {
public TestAOPSchemaAdvisors() {
super("classpath:spring-aop-schema-advisors.xml");
}
@Test
public void testSave() {
InvokeService service = super.getBean("invokeService");
service.invoke();
System.out.println("end...");
service.invokeException();
}
}
- 测试结果:
Try times : 1
InvokeService ......
end...
Try times : 1
Try times : 2
Try times : 3
Try times : 4
Try error : 4
十五、Spring AOP API
这一章节内容挺多挺杂的,就直接上实例吧:
配置文件:
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="moocBeforeAdvice" class="com.twx.aop.api.MoocBeforeAdvice"></bean>
<bean id="moocAfterReturningAdvice" class="com.twx.aop.api.MoocAfterReturningAdvice"></bean>
<bean id="moocMethodInterceptor" class="com.twx.aop.api.MoocMethodInterceptor"></bean>
<bean id="moocThrowsAdvice" class="com.twx.aop.api.MoocThrowsAdvice"></bean>
<bean id="bizLogicImplTarget" class="com.twx.aop.api.BizLogicImpl"></bean>
<bean id="pointcutBean" class="org.springframework.aop.support.NameMatchMethodPointcut">
<property name="mappedNames">
<list>
<value>sa*</value>
</list>
</property>
</bean>
<bean id="defaultAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="advice" ref="moocBeforeAdvice" />
<property name="pointcut" ref="pointcutBean" />
</bean>
<bean id="bizLogicImpl" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<ref bean="bizLogicImplTarget"/>
</property>
<property name="interceptorNames">
<list>
<value>defaultAdvisor</value>
<value>moocAfterReturningAdvice</value>
<value>moocMethodInterceptor</value>
<value>moocThrowsAdvice</value>
</list>
</property>
</bean>
</beans>
前面4个mocc开头的bean对应的是spring aop api 的接口实现类,切入点是以sa开头的方法。
bizLogicImplTarget是被代理对象。
测试类:
package com.twx.aop;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import com.twx.aop.api.BizLogic;
import com.twx.test.base.UnitTestBase;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestAOPAPI extends UnitTestBase {
public TestAOPAPI() {
super("classpath:spring-aop-api.xml");
}
@Test
public void testSave() {
BizLogic logic = (BizLogic)super.getBean("bizLogicImpl");
logic.save();
}
}
当super.getBean(“bizLogicImpl”)时,返回的是代理对象bizLogicImplTarget。
当调用bizLogicImplTarget的save()方法时,就会切入执行interceptorNames下所列举出来的实现spring aop api接口的类方法。