当前位置: 移动技术网 > IT编程>开发语言>Java > Spring AOP创建AroundAdvice实例

Spring AOP创建AroundAdvice实例

2019年07月07日  | 移动技术网IT编程  | 我要评论

     aroundadvice

        1、在方法之前和之后来执行相应的操作

        2、实现methodinterceptor接口

 

接口文件:

 

public interface ihello {
   public void sayhello(string str);
}
public class hello implements ihello {
    @override
    public void sayhello(string str) {
    	system.out.println("你好"+str);
    }
}

 

  sayaroundadvice文件:

public class sayaroundadvice implements methodinterceptor {

	@override
	public object invoke(methodinvocation arg0) throws throwable {
		// todo auto-generated method stub
		object result=null;
		
		system.out.println("around在方法执行前做事情!");
		
		result=arg0.proceed();
		
		system.out.println("around在方法执行后做事情!");
		
		return result;
	}

}

  main文件:

public class maintest {

	public static void main(string[] args) {
		// todo auto-generated method stub
	    applicationcontext context=new classpathxmlapplicationcontext("applicationcontext.xml");
	    
	    ihello hello=(ihello)context.getbean("helloproxy");
	    hello.sayhello("访客");
	}

}

  

applicationcontext.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<!doctype beans public "-//spring//dtd bean 2.0//en" 
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
    <!-- 建立目标对象实例 -->
	<bean id="bean_hello" class="com.pb.hello" />
	<!-- 创建around advice实例 -->
	<bean id="ssd" class="com.pb.sayaroundadvice" />
	<!-- 建立代理对象 -->
	<bean id="helloproxy" class="org.springframework.aop.framework.proxyfactorybean">
	    <!-- 设置代理的接口 -->
	    <property name="proxyinterfaces">
			<value>com.pb.ihello</value>
		</property>
		<!-- 设置目标对象实例 -->
		<property name="target">
			<ref bean="bean_hello"/>
		</property>
		<!-- 设置advice实例 -->
		<property name="interceptornames">
			<list>
			 	 <value>ssd</value>
			</list>
		</property>
	</bean>
</beans>

  执行效果:

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网