Thursday, October 8, 2015

Spring data simple example

1.intro

Very often, on DB level there are a lot of classes(DAOs) with similar methods:

To avoid that  - there are  lot of different strategies. In my blog a described some of them : 1. using genericDao    2. EasyJDBC tool
Spring Data - another approach  : you just  have to create an interface (which can be extended from  default CRUD repository) and leave it without implementation. String will generate implementation for you!

2.project structure

Everything is pretty simple : one entity (Category), one dao-repository(CategoryRepository) interface, one config class for spring and application runner(class with main procedure):



3. project pom.xml

Just 3 dependencies here :  spring data, persistence api for annotation support, H2 database.
 
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demien</groupId>
    <artifactId>sdata</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.3.4.RELEASE</version>
    </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.2.5.Final</version>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>2.2</version>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.3.173</version>
        </dependency>

    </dependencies>

</project>

4. app.properties

Properties for H2 DB and hibernate
 
#DB properties:db.driver=org.h2.Driverdb.url=jdbc:h2:~/testdb.username=sadb.password=sa
#Hibernate Configuration:db.hibernate.dialect=org.hibernate.dialect.H2Dialectdb.hibernate.show_sql=falsedb.entitymanager.packages.to.scan=com.demien.sdata.domaindb.hibernate.hbm2ddl.auto = create

 

5. test entity

It's a very simple entity with persistence api annotations. 

package com.demien.sdata.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity(name = "CATEGORY")
public class Category {

    @Id    @Column(name = "CATEGORY_ID")
    private Long categoryId;

    @Column(name="CATEGORY_NAME")
    private String categoryName;

    @Column(name = "CATEGORY_DESCRIPTION")
    private String categoryDescription;

    @Column(name="PARENT_CATEGORY_ID")
    private Long parentCategoryId;

    public Category() {}

    public Long getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Long categoryId) {
        this.categoryId = categoryId;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public String getCategoryDescription() {
        return categoryDescription;
    }

    public void setCategoryDescription(String categoryDescription) {
        this.categoryDescription = categoryDescription;
    }

    public Long getParentCategoryId() {
        return parentCategoryId;
    }

    public void setParentCategoryId(Long parentCategoryId) {
        this.parentCategoryId = parentCategoryId;
    }

    @Override    public String toString() {
        return "Category{" +
                "categoryId=" + categoryId +
                ", categoryName='" + categoryName + '\'' +
                '}';
    }
}

6. repository

As I mention before, we just have to create interface - implementation will be created by Spring. Interface extended from JpaRepository - it has definition of all base db methods (like save, find, delete...). I added only one custom method to interface, and again : it's just a method without implementation. 


package com.demien.sdata.repository;

import com.demien.sdata.domain.Category;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository(value = "CategoryRepository")
public interface CategoryRepository extends JpaRepository<Category, Long> {

    @Query("FROM CATEGORY where CATEGORY_NAME like %?1% ")
    List<Category> findByPattern(String pattern);
}

7. spring config

XML configs are not very popular at modern time, so I used XML-less Spring configuration. 

package com.demien.sdata;

import org.hibernate.ejb.HibernatePersistence;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Properties;

@Configuration@EnableTransactionManagement@ComponentScan("com.demien.sdata")
@PropertySource("classpath:app.properties")
@EnableJpaRepositories("com.demien.sdata.repository")
public class AppConfig {


private static final String PROP_DATABASE_DRIVER = "db.driver";
private static final String PROP_DATABASE_PASSWORD = "db.password";
private static final String PROP_DATABASE_URL = "db.url";
private static final String PROP_DATABASE_USERNAME = "db.username";
private static final String PROP_HIBERNATE_DIALECT = "db.hibernate.dialect";
private static final String PROP_HIBERNATE_SHOW_SQL = "db.hibernate.show_sql";
private static final String PROP_ENTITYMANAGER_PACKAGES_TO_SCAN = "db.entitymanager.packages.to.scan";
private static final String PROP_HIBERNATE_HBM2DDL_AUTO = "db.hibernate.hbm2ddl.auto";

@Resourceprivate Environment env;

    @Bean    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName(env.getRequiredProperty(PROP_DATABASE_DRIVER));
        dataSource.setUrl(env.getRequiredProperty(PROP_DATABASE_URL));
        dataSource.setUsername(env.getRequiredProperty(PROP_DATABASE_USERNAME));
        dataSource.setPassword(env.getRequiredProperty(PROP_DATABASE_PASSWORD));

        return dataSource;
    }

    @Bean    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistence.class);
        entityManagerFactoryBean.setPackagesToScan(env.getRequiredProperty(PROP_ENTITYMANAGER_PACKAGES_TO_SCAN));

        entityManagerFactoryBean.setJpaProperties(getHibernateProperties());

        return entityManagerFactoryBean;
    }

    @Bean    public JpaTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());

        return transactionManager;
    }

    private Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", env.getRequiredProperty(PROP_HIBERNATE_DIALECT));
        properties.put("hibernate.show_sql", env.getRequiredProperty(PROP_HIBERNATE_SHOW_SQL));
        properties.put("hibernate.hbm2ddl.auto", env.getRequiredProperty(PROP_HIBERNATE_HBM2DDL_AUTO));

        return properties;
    }
}
 

8. main runner

I'm starting Spring context and testing main  repository methods here

package com.demien.sdata;

import com.demien.sdata.domain.Category;
import com.demien.sdata.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.Arrays;

/** * Created by dmitry on 05.10.15. */public class App {




    private static ApplicationContext applicationContext;
    public static void main(String args[]) {
        applicationContext=new AnnotationConfigApplicationContext(AppConfig.class);
        new App().test();
    }

    public void test() {
        CategoryRepository categoryRepository=(CategoryRepository)applicationContext.getBean("CategoryRepository");

        Category  category=new Category();
        category.setCategoryId(1l);
        category.setCategoryName("Test 1");
        categoryRepository.save(category);

        category=new Category();
        category.setCategoryId(2l);
        category.setCategoryName("Test 2");

        categoryRepository.save(category);

        System.out.println("\n categoryRepository.findAll()");
        System.out.println(Arrays.toString(categoryRepository.findAll().toArray()));

        System.out.println("\n categoryRepository.findOne(1l)");
        System.out.println(categoryRepository.findOne(1l));


        System.out.println("\n categoryRepository.findByPattern(2)");
        System.out.println(Arrays.toString(categoryRepository.findByPattern("2").toArray()));


        category.setCategoryName("new name");
        categoryRepository.save(category);
        System.out.println("\n UPDATE to new name for element with id=2");
        System.out.println(Arrays.toString(categoryRepository.findAll().toArray()));

        categoryRepository.delete(category);
        System.out.println("\n DELETE of element with id=2");
        System.out.println(Arrays.toString(categoryRepository.findAll().toArray()));


    }
}

9. results 

Everything is working as expected:


 categoryRepository.findAll()
[Category{categoryId=1, categoryName='Test 1'}, Category{categoryId=2, categoryName='Test 2'}]

 categoryRepository.findOne(1l)
Category{categoryId=1, categoryName='Test 1'}

 categoryRepository.findByPattern(2)
[Category{categoryId=2, categoryName='Test 2'}]

 UPDATE to new name for element with id=2
[Category{categoryId=1, categoryName='Test 1'}, Category{categoryId=2, categoryName='new name'}]

 DELETE of element with id=2
[Category{categoryId=1, categoryName='Test 1'}]

Process finished with exit code 0


10. the end

Spring data - very good option to be used on DAO level of application.
Full source code can be downloaded from here.

Saturday, October 3, 2015

Spring boot - simple example

1. Intro

Of course, it's very easy to create rest-web application in java : there are a lot of frameworks and libraries for that, for example Spring MVC, Apache CXF, etc.
But how to test created application ? First of all, you have to build .war file. After that - deploy it to Tomcat. Ok, now application is running, but again : how to test rest services ?  I, for example created for that tool which is using apache.http.client to call rest services. Also I created tool for starting(and testing) application using embedded-jetty, without deploing it to tomcat. And I think, a lot of developers have have such tools.

Spring boot - created to make starting of application and it testing very east out-of-the-box: http://projects.spring.io/spring-boot/


2. Project structure

Project can be generated using online constructor : http://start.spring.io/
 
I created simple project with just one rest-controller, one repository for emulating working with DB, one domain object and one test class. Project was generated by online constructor, I just added new files, renamed main "run" file to App and removed test file.



3. pom.xml

It also was generated by constructor, I just added one more dependency (com.jayway.jsonpath).

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>com.demien</groupId>
   <artifactId>sboot</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.2.6.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>

      <dependency>
         <groupId>com.jayway.jsonpath</groupId>
         <artifactId>json-path</artifactId>
         <scope>test</scope>
      </dependency>

   </dependencies>
   
   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>
   

</project>



4. Entity

Very simple entity class with just 2 fields.
package com.demien.sboot;

public class TestEntity {
    private Integer entityId;
    private String entityName;

    public TestEntity() {}

    public Integer getEntityId() {
        return entityId;
    }

    public void setEntityId(Integer entityId) {
        this.entityId = entityId;
    }

    public String getEntityName() {
        return entityName;
    }

    public void setEntityName(String entityName) {
        this.entityName = entityName;
    }
}

5. Repository 

- simulation of DB repository. I used static ArrayList for storing elements of TestEntity type. And only 3 operations was implemented : add, getById and getAll.

package com.demien.sboot;

import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


@Componentpublic class TestRepository {
    private static List<TestEntity> storage=new ArrayList<TestEntity>();


    public TestEntity add(TestEntity entity) {
        entity.setEntityId(storage.size()+1);
        storage.add(entity);
        return entity;
    }

    public TestEntity getById(Long entityId) {
        return storage.get(  entityId.intValue()-1);
    }

    public int getMaxId(){
        return storage.size();
    }

    public List<TestEntity> getAll() {
        return storage;
    }



}

6. Controller

Creation of rest-controller is not very hard : just few annotations and calls of repository's methods. 

package com.demien.sboot;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController@RequestMapping("/entity")
public class TestController {

    @Autowired    TestRepository repository;

    @RequestMapping("/hello")
    public String sayHello() {
        return "Hello, world!";
    }

    @RequestMapping(value = "add",  method = RequestMethod.POST)
    public @ResponseBody    TestEntity add(@RequestBody TestEntity entity) {
        TestEntity result=repository.add(entity);
        return result;
    }

    @RequestMapping(value="get/{entityId}", method = RequestMethod.GET)
    public TestEntity get(@PathVariable Long entityId) {
        return repository.getById(entityId);
    }

    @RequestMapping(value="getall", method = RequestMethod.GET)
    public List<TestEntity> getAll() {
        return repository.getAll();
    }

}


7. Application main(starter) file

This file was generated by constructor, I just renamed it. Just after creation of controller we can run App file and it will run our application on embedded-tomcat. And we can test our application by opening in browser URL: http://localhost:8080/entity/hello - it should return "Hello, world!"

As you can see - running of application is VERY easy. It even can be packed into jar file and running using java -jar ...... without tomcat!

package com.demien.sboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplicationpublic class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

8. Test of our controller

Test class class of our controller, from the first look, seems to be complicated - that it just because it has some logic related with json-transformations and some init lines of code for mockMvc. In real life all stuff like this, can be placed in parent test-base-class.
   Logic related with testing itself(methods with @Test annotation) - is very simple and clear.

package com.demien.sboot;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.mock.http.MockHttpOutputMessage;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.hasSize;


@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = App.class)
@WebAppConfigurationpublic class TestControllerTest {

    private MockMvc mockMvc;

    @Autowired    TestRepository repository;


    private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
            MediaType.APPLICATION_JSON.getSubtype(),
            Charset.forName("utf8"));

    private HttpMessageConverter mappingJackson2HttpMessageConverter;

    @Autowired    void setConverters(HttpMessageConverter<?>[] converters) {

        this.mappingJackson2HttpMessageConverter = Arrays.asList(converters).stream().filter(
                hmc -> hmc instanceof MappingJackson2HttpMessageConverter).findAny().get();

        Assert.assertNotNull("the JSON message converter must not be null",
                this.mappingJackson2HttpMessageConverter);
    }

    @Autowired    private WebApplicationContext webApplicationContext;

    protected String json(Object o) throws IOException {
        MockHttpOutputMessage mockHttpOutputMessage = new MockHttpOutputMessage();
        this.mappingJackson2HttpMessageConverter.write(o, MediaType.APPLICATION_JSON, mockHttpOutputMessage);
        return mockHttpOutputMessage.getBodyAsString();
    }

    @Before    public void init()  {
        this.mockMvc = webAppContextSetup(webApplicationContext).build();
    }

    @Test    public void helloTest() throws Exception {
        mockMvc.perform(get("/entity/hello"))
                .andExpect(status().isOk())
                .andExpect(content().string("Hello, world!"));
    }

    @Test    public void addTest() throws Exception {
        TestEntity entity=new TestEntity();
        entity.setEntityName("Test");

        mockMvc.perform(post("/entity/add/")
                .content(this.json(entity))
                .contentType(contentType))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.entityId", is(repository.getMaxId())))
                .andExpect(jsonPath("$.entityName", is(entity.getEntityName())))
        ;
    }

    @Test    public void getTest() throws Exception {
        TestEntity entity=new TestEntity();
        entity.setEntityName("TestGet");
        entity=repository.add(entity);

        mockMvc.perform(get("/entity/get/" + entity.getEntityId()))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.entityId", is(entity.getEntityId())))
                .andExpect(jsonPath("$.entityName", is(entity.getEntityName())))
        ;

    }

    @Test    public void getAllTest() throws Exception {
        TestEntity entity=new TestEntity();
        entity.setEntityName("TestGetAll");
        entity=repository.add(entity);

        mockMvc.perform(get("/entity/getall"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(repository.getAll().size())))
        ;

    }
}
 

9. The end

Spring boot helped us to create rest application with can be run very easy. And also this application is very easy for testing. Full source code can be downloaded from here.

Sunday, August 16, 2015

JMX simple example

1. Intro

The JMX technology provides a simple, standard way of managing resources such as applications, devices, and services. Because the JMX technology is dynamic, you can use it to monitor and manage resources as they are created, installed and implemented. You can also use the JMX technology to monitor and manage the Java Virtual Machine (Java VM).

How it works : when our application is running, we can connect to it using jconsole application (located in JAVA_HOME/bin directory) : 

After that we have to switch to tab "MBeans", select our application, and we can view and change(if we want) IN RUNTIME some application variables: 



We have just to change variable (or execute method) using jconsole - and it will have the same effect like it was changed(or method was executed) inside our application. 


2. Project structure

Everything is pretty simple :)  



3. pom.xml file

Jmx is part of Java SDK, so we don't need any dependencies at all.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demien.jmxtest</groupId>
    <artifactId>JMXTest</artifactId>
    <version>1.0-SNAPSHOT</version>

    
</project>

4. JMX Bean 

First we need to create interface for our class  which we want to make visible/usable for jconsole. And , ofcource, we also need implementation.  Important thing here - naming. Interface have to be ending with MBean. Implementation - it has to be the same name as for interface, but without MBean.



package com.demien.jmxtest;

public interface TestJmxConfigMBean {
    String getValue();
    void setValue(String value);

    Long getRunningTime();
    void resetRunnigTime();
} 
 
 
 

package com.demien.jmxtest;

import java.util.Date;

public class TestJmxConfig implements TestJmxConfigMBean {

    private String value="Start value";
    private Date startTime=new Date();

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value=value;
    }

    public Long getRunningTime() {
        Date currectTime=new Date();
        return currectTime.getTime()-startTime.getTime();
    }

    public void resetRunnigTime() {
        startTime=new Date();
    }
}




5. Application runner

We need to register our MBen at MBeanServer. After that it will be visible by jconsole. 
Other logic is very simple : just printing values from our MBean every 10 seconds. 


package com.demien.jmxtest;

import javax.management.*;
import java.lang.management.ManagementFactory;

public class App {

    static TestJmxConfig mBean = new TestJmxConfig();

    public static void registerMbean() throws Exception {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName name = new ObjectName("com.demien.jmxtest:type=TestJmxConfig");
        mbs.registerMBean(mBean, name);

    }

    public static void main(String[] args) throws Exception {
        registerMbean();
        while (true) {
            System.out.println("mbeanData: RunningTime="+mBean.getRunningTime()+"  Value="+mBean.getValue());
            Thread.sleep(10000);
        }
    }
}



6. Results of execution

At the beginning, application is printing "Start value". At running time, between 20 and 30 seconds of execution I changed value, So for rinning time 30028 - we have value which I entered in jconsole. 
Little later(after 40 seconds of program running) I executed operation "ResetRunnigTime". So time began to count again from 0. 

mbeanData: RunningTime=28  Value=Start value
mbeanData: RunningTime=10028  Value=Start value
mbeanData: RunningTime=20028  Value=Start value
mbeanData: RunningTime=30028  Value=Value was changed ! 
mbeanData: RunningTime=40028  Value=Value was changed ! 
mbeanData: RunningTime=3418  Value=Value was changed ! 

mbeanData: RunningTime=13418  Value=Value was changed ! 

7. The end 

 Source code can be downloaded from here.

Wednesday, August 12, 2015

AOP for logging and perfomance testing

1. Intro

From wiki, what is AOP ?  :
In computing, aspect-oriented programming (AOP) is a patented[1] programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. It does so by adding additional behavior to existing code (an advice) without modifying the code itself, instead separately specifying which code is modified via a "pointcut" specification, such as "log all function calls when the function's name begins with 'set'". This allows behaviors that are not central to the business logic (such as logging) to be added to a program without cluttering the code core to the functionality. AOP forms a basis for aspect-oriented software development.

Little bit complicated explanation, as for me :) In shorts, AOP - technology which can give you ability to create for existing code(without it modification) "triggers" (by analogy to DB) . Triggers(aspects) can be activated when program execution, for example reaches some method. That behaviour can be very usefull for : 
1. Logging 
2. Perfomance testing. 
For example we have an application which is working, but, one day, we found that something is working too slow, and we have no idea where exactly. So we decided to add aditional logging with information regarding time of method execution. 
Advantages with using AOP for that purpose are obvious : we have just to create "logger" class without any code changes in our application. 


2. project structure

I created several "levels" to demonstarte logging: 
- UI level : TestUIController
- Service level : TestService
- Dao level : TestDao 



Also : 
- App - main application runner. 
- AopInterceptor - our class which will use AOP for logging 


3. pom.xml file 

Here are just dependencies for spring and aspectj: 


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demien.aoplogging</groupId>
    <artifactId>aoplogging</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.0.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjtools</artifactId>
            <version>1.8.6</version>
        </dependency>

    </dependencies>

</project>


4. application context file 

There are few classes with "logic" and logger class. Also I showed that logger can be configured by entering parameters in context file. If logger is not needed anymore - logger bean can be just commented in context file. 

<?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-3.0.xsd"

        >

    <bean id="dao" class="com.demien.aoplogging.TestDao"/>
    <bean id="service" class="com.demien.aoplogging.TestService">
        <property name="dao">
            <ref bean="dao"/>
        </property>
    </bean>

    <bean id="controller" class="com.demien.aoplogging.TestUIController">
        <property name="service">
            <ref bean="service"/>
        </property>
    </bean>

    <!-- The Aspect itself. -->
    <aop:aspectj-autoproxy />
    <bean id="aopInterceptor" class="com.demien.aoplogging.AopInterceptor">
       
        <constructor-arg>
            <map>
                <entry key="TIME_FORMAT"  value="sec"></entry>
            </map>
        </constructor-arg>
        
    </bean>


</beans>


5. AOP Logger. 

All logic are located in doAround method. Also, for example,  I added logic with parameters which can be passed from context file. Here we can configure format of time intervals : miliseconds/seconds/minutes. 

package com.demien.aoplogging;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import java.util.Date;
import java.util.Map;

@Aspect
public class AopInterceptor {

    enum TIME_FORMAT {ms, sec, min};
    TIME_FORMAT currentTimeFormat=TIME_FORMAT.ms;


    public AopInterceptor() {}

    public AopInterceptor(Map<String, String> params) {
        String timeFormat=params.get("TIME_FORMAT");
        if (timeFormat!=null) {
            currentTimeFormat=TIME_FORMAT.valueOf(timeFormat);
        }
    }

    @Around("execution(* *(..))")
    public void doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        String className=joinPoint.getTarget().getClass().getName();
        String methodName=joinPoint.getSignature().getName();

        Long startTime=getCurrentTime();
        log("Started : ["+className+"] : " + methodName);
        joinPoint.proceed();
        Long endTime=getCurrentTime();

        log("Finished : [" + className + "] : " + methodName+" ExecutionTime is: "+getExecutionInterval(startTime)+currentTimeFormat);
    }

    private Long getCurrentTime() {
        return (new Date()).getTime();
    }

    private Long getExecutionInterval(Long startTime) {
        Long endTime=getCurrentTime();
        Long interval=endTime-startTime;
        switch (currentTimeFormat) {
            case min: interval=interval/60;
            case sec: interval=interval/1000;
            default: break;
        }
        return interval;
    }


    private void log(final String messageToLog)
    {
        // here have to be logging to some specific location
        System.out.println(messageToLog);
    }
}


6. Other classes.

Few very simple classes with dependencies managed by Spring. it's just a simulation of big complex application:   UI is calling controller method, controller is calling service method, service method is calling  dao method. 

package com.demien.aoplogging;

public class TestUIController {
    private TestService service;

    public void setService(TestService service) {
        this.service = service;
    }

    public void doSomeAction() {
            service.doServiceAction();
    }
}






package com.demien.aoplogging;

public class TestService {
    private TestDao dao;

    public void setDao(TestDao dao) {
        this.dao = dao;
    }


    public void doServiceAction() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        dao.doDaoAction();
    }
}







package com.demien.aoplogging;

public class TestDao {

    public void doDaoAction(){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("done!");
    }

}





package com.demien.aoplogging;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    public static void main(String[] args) {

        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("/application-context.xml");
        TestUIController controller=(TestUIController)context.getBean("controller");
        controller.doSomeAction();
    }
}




7. Results of execution.

All our executions were logged with timings values:

Started : [com.demien.aoplogging.TestUIController] : doSomeAction
Started : [com.demien.aoplogging.TestService] : doServiceAction
Started : [com.demien.aoplogging.TestDao] : doDaoAction
done!
Finished : [com.demien.aoplogging.TestDao] : doDaoAction ExecutionTime is: 1sec
Finished : [com.demien.aoplogging.TestService] : doServiceAction ExecutionTime is: 3sec

Finished : [com.demien.aoplogging.TestUIController] : doSomeAction ExecutionTime is: 3sec


8.The end. 

Goal is reached. We have a logging without any changes in our business-logic classes - but just by adding AOP logger into application. Source code can be downloaded from here.