Руководство по Spring. АОП в Spring с использованием XML (пример приложения).

Прежде, чем использовать AOP в нашем Srping-приложении, нам необходимо добавить новые зависимости (spring-aop и aspectjtools) в наш pom.xml файл. Сами зависимости Вы можете найти по этой ссылке и по этой ссылке.

Пример приложения:

Исходный код проекта можно скачать по ЭТОЙ ССЫЛКЕ.

Структура проекта

aopDeveloperStructure

Класс Developer.java


package net.proselyte.aop;

public class Developer {
    private String name;
    private String specialty;
    private Integer experience;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSpecialty() {
        return specialty;
    }

    public void setSpecialty(String specialty) {
        this.specialty = specialty;
    }

    public Integer getExperience() {
        return experience;
    }

    public void setExperience(Integer experience) {
        this.experience = experience;
    }

    public void throwSomeMysticException(){
        System.out.println("We have some strange and mystic exception here:");
        throw new ClassCastException();
    }

    @Override
    public String toString() {
        return "Developer:\n" +
                "Name: " + name + '\n' +
                "Specialty: " + specialty + '\n' +
                "Experience: " + experience + "\n";
    }
}

Класс Logging.java


package net.proselyte.aop;

public class Logging {
    public void beforeAdvice() {
        System.out.println("Now we are going to initiate developer's profile.");
    }

    public void afterAdvice() {
        System.out.println("Developer's profile has been initiated.");
    }

    public void afterReturningAdvice(Object someValue) {
        System.out.println("Value: " + someValue.toString());
    }

    public void inCaseOfExceptionThrowAdvice(ClassCastException e) {
        System.out.println("We have an exception here: " + e.toString());
    }

}

Конфигурационный файл aop-developer-config.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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

    <aop:config>
        <aop:aspect id="log" ref="logging">
            <aop:pointcut id="selectAll"
                          expression="execution(* net.proselyte.aop.*.*(..))"/>
            <aop:before pointcut-ref="selectAll" method="beforeAdvice"/>
            <aop:after pointcut-ref="selectAll" method="afterAdvice"/>
            <aop:after-returning pointcut-ref="selectAll"
                                 returning="someValue"
                                 method="afterReturningAdvice"/>
            <aop:after-throwing pointcut-ref="selectAll"
                                throwing="e"
                                method="inCaseOfExceptionThrowAdvice"/>
        </aop:aspect>
    </aop:config>

    <!-- Definition for developer bean -->
    <bean id="developer" class="net.proselyte.aop.Developer">
        <property name="name"  value="Proselyte" />
        <property name="specialty"  value="Java Developer" />
        <property name="experience"  value="3" />
    </bean>

    <!-- Here we define logging aspect -->
    <bean id="logging" class="net.proselyte.aop.Logging"/>

</beans>

Класс AopDeveloperRunner.java


package net.proselyte.aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AopDeveloperRunner {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("aop-developer-config.xml");
        Developer developer = (Developer) context.getBean("developer");

        System.out.println(developer);
        developer.throwSomeMysticException();
    }
}

Результат работ программы

aopDeveloperResult

В этом пример мы рассмотрели основы применения АОП в Spring с применением конфигурационного XML-файла.