spring aop使用

使用spring aop 依赖外来jar:  aopalliance.jar 、aspectjweaver.jar

简单打印log测试

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

    <!-- services -->
   <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="5" />
    <property name="maxPoolSize" value="10" />
    <property name="queueCapacity" value="25" />
    </bean>
    <bean id="taskExecutorExample" class="com.whty.service.TaskExecutorExample">
    <constructor-arg ref="taskExecutor" />
    </bean>
</beans>

<?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.xsd">
    <!-- services -->
    <aop:config>
    <aop:aspect  ref="logBean">
        <aop:pointcut id="businessService" expression="execution(* com.whty.service.*.*(..))"/>
        <aop:before pointcut-ref="businessService" method="print"/>
    </aop:aspect>
    </aop:config>

    <bean id="logBean" class="com.whty.service.LogBean">
    </bean>
</beans>

package com.whty.service;

import org.springframework.core.task.TaskExecutor;

public class TaskExecutorExample {

    private class MessagePrinterTask implements Runnable {

        private String message;

        public MessagePrinterTask(String message) {
            this.message = message;
        }

        public void run() {
            System.out.println(message);
        }

    }

    private TaskExecutor taskExecutor;

    public TaskExecutorExample(TaskExecutor taskExecutor) {
        this.taskExecutor = taskExecutor;
    }

    public void printMessages() {
        for(int i = 0; i < 25; i++) {
            taskExecutor.execute(new MessagePrinterTask("Message" + i));
        }
    }

}

package com.whty.service;

import org.apache.log4j.Logger;

public class LogBean {
  public Logger logger=Logger.getLogger(LogBean.class);
  public void print(){
      logger.info("打印log!");
  }
}

public class SpringContainer {
    public static void main(String[] args) throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"services.xml","spring-aop.xml"});
        TaskExecutorExample t = context.getBean("taskExecutorExample",
                TaskExecutorExample.class);
        t.printMessages();
       
    }
}
原文地址:https://www.cnblogs.com/sinslu/p/4277169.html