Add context to our application.
main/resources/applicationContext.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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config /> <context:component-scan base-package="com.pluralsight" /> </beans>
Using annotation for @Service @Repository @Controller:
/repository/HibernateCustomerRepositoryImpl.java:
package com.pluralsight.repository; import com.pluralsight.model.Customer; import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.List; @Repository("customerRepository") public class HibernateCustomerRepositoryImpl implements CustomerRepository { @Override public List<Customer> findAll() { List<Customer> customers = new ArrayList<>(); Customer customer = new Customer(); customer.setFirstname("Byran"); customer.setLastname("John"); customers.add(customer); return customers; } }
/service/CustomerServiceImpl.java:
We use @Autowrie for the member of Repository.
package com.pluralsight.service; import com.pluralsight.model.Customer; import com.pluralsight.repository.CustomerRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service("customerService") public class CustomerServiceImpl implements CustomerService { @Autowired private CustomerRepository customerRepository; @Override public List<Customer> findAll() { return customerRepository.findAll(); } }
We can also use Setter Injection:
private CustomerRepository customerRepository; @Autowired public CustomerServiceImpl (CustomerRepository customerRepository) { this.customerRepository = customerRepository; }
We can also use Constructor Injection:
private CustomerRepository customerRepository; @Autowired public CustomerServiceImpl (CustomerRepository customerRepository) { this.customerRepository = customerRepository; }
After using Annotations & Autowired, we code looks simple and decoupled