Home > Java > Spring Auto Component Scanning

Spring Auto Component Scanning

February 24, 2014 Leave a comment Go to comments

Pada umumnya kita mendeklarasikan semua bean di file XML bean configuration, sehingga Spring container dapat mendeteksi bean tersebut. Spring sebenarnya dapat melakukan auto scan bean tersebut menggunakan annotation dan jadi lebih sederhana. Berikut ini example sederhana CRUD satu table ( menggunakan service dan dao layer ).

  • Table books
Book Table

Book Table

  • Model layer ( Book.java )


package com.spring.model;

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

@Entity
@Table(name="books")
public class Book {
@Id
@Column(name="id")
@GeneratedValue
private int id;

@Column(name="book_name")
private String bookName;

@Column(name="author")
private String author;

@Column(name="price")
private int price;

@Column(name="qty")
private int quantity;

public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookName() {
return bookName;
}
public void setAuthor(String author) {
this.author = author;
}
public String getAuthor() {
return author;
}
public void setPrice(int price) {
this.price = price;
}
public int getPrice() {
return price;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getQuantity() {
return quantity;
}
}

  • DAO layer

BookDao interface ( BookDao.java )

package com.spring.dao;

import java.util.List;

import com.spring.model.Book;

public interface BookDao {
public void addBook(Book book);
public void updateBook(Book book);
public List<Book> listBooks();
public Book getBookById(Integer bookId);
public void removeBook(Integer id);
}

BookDaoImpl ( BookDaoImpl.java )

package com.spring.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.spring.model.Book;

@Repository
public class BookDaoImpl implements BookDao{

@Autowired
private SessionFactory sessionFactory;

@Override
public void addBook(Book book) {

sessionFactory.getCurrentSession().save(book);
}

@Override
public void removeBook(Integer id) {
Book book = (Book)sessionFactory.getCurrentSession()
.load(Book.class, id);
if(null != book) {
sessionFactory.getCurrentSession().delete(book);
}
}

@Override
@SuppressWarnings("unchecked")
public List<Book> listBooks() {
return sessionFactory.getCurrentSession()
.createQuery("from Book").list();
}

@Override
public void updateBook(Book book) {
sessionFactory.getCurrentSession().update(book);
}

@Override
@SuppressWarnings("unchecked")
public Book getBookById(Integer bookId) {
Session session = sessionFactory.getCurrentSession();
List<Book> list = session.createQuery("from Book b where b.id = :bookId")
.setParameter("bookId", bookId)
.list();
return list.size() > 0 ?(Book)list.get(0): null;
}
}

  • Service layer

BookService interface ( BookService.java )

package com.spring.service;

import java.util.List;
import com.spring.model.Book;

public interface BookService {
public void addBook(Book book);
public void updateBook(Book book);
public Book getBookById(Integer bookId);
public List<Book> listBooks();
public void removeBook(Integer id);
}

BookServiceImpl ( BookServiceImpl.java )

package com.spring.service;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spring.dao.BookDao;
import com.spring.model.Book;

@Service
public class BookServiceImpl implements BookService{
@Autowired
private BookDao bookDao;

@Transactional
public void addBook(Book book) {
bookDao.addBook(book);
}

@Transactional
public void removeBook(Integer id) {
bookDao.removeBook(id);
}

@Transactional
public List<Book> listBooks() {
return bookDao.listBooks();
}

@Transactional
public void updateBook(Book book) {
bookDao.updateBook(book);
}

@Transactional
public Book getBookById(Integer bookId) {
return bookDao.getBookById(bookId);
}
}

  • Main class


package com.spring.main;

import java.util.Iterator;
import java.util.List;

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

import com.spring.model.Book;
import com.spring.service.BookService;
import com.spring.service.BookServiceImpl;

public class Main {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("SpringBean.xml");
BookService bsImpl = (BookService) context.getBean("bookServiceImpl");

/*Insert*/
Book book = new Book();
book.setAuthor("JK Rowling");
book.setBookName("Harry Potter");
book.setPrice(100000);
book.setQuantity(100);
bsImpl.addBook(book);

/*Select*/
Book bookDua = bsImpl.getBookById(1);
System.out.println(bookDua.getId());
System.out.println(bookDua.getAuthor());
System.out.println(bookDua.getPrice());
System.out.println(bookDua.getQuantity());
System.out.println(bookDua.getBookName());

/*Update*/
Book bookTiga = bookDua;
bookTiga.setQuantity(11);
bsImpl.updateBook(bookTiga);

/*Select All */
List <Book> bookList = bsImpl.listBooks();
Iterator iter = bookList.iterator();
while(iter.hasNext()){
Book bookEmpat = (Book) iter.next();
System.out.println(bookEmpat.getAuthor());
System.out.println(bookEmpat.getBookName());
}
/*Delete*/
bsImpl.removeBook(1);

}
}

  • Bean configuration xml ( SpringBean.xml )


...
<context:annotation-config />
<context:component-scan base-package="com.spring" />

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>db.properties</value>
</property>
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.spring.model.Book</value>
</list>
</property>
</bean>
<tx:annotation-driven/>

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
...

  • db properties


jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springdb
jdbc.username=root
jdbc.password=

  • Project Structure
Project Structure

Project Structure

Pada Spring terdapat 4 type auto components scan annotation.

  1. @Component : Annotation bersifat generic yang dapat digunakan pada semua layer
  2. @Service : Annotation class pada service layer
  3. @Repository : Annotation class pada dao layer
  4. @Controller : Annotation class pada presentation layer ( digunakan biasanya di Spring MVC )

Secara umum 4 annotation hampir tidak ada perbedaan, namun untuk readability penggunaan annotation tersebut disesuaikan layer class.

Referensi : dari berbagai sumber.
Semoga bermanfaat.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: