Hejka!
Przerabiam sobie kurs na Pluralsight
.
Mam przykładowy kod
@Repository("customerRepository")
public class HibernateCustomerRepositoryImpl implements CustomerRepository {
@Override
public List<Customer> findAll() {
List<Customer> customers = new ArrayList<>();
Customer customer = new Customer();
customer.setFirstName("Bryan");
customer.setLastName("Hansen");
customers.add(customer);
return customers;
}
}
i coś takiego:
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();
}
}
Konfiguracja w xml to:
<context:annotation-config/>
<context:component-scan base-package="com.pluralsight" />
Jaka jest różnica między wstrzykiwaniem tak jak wyżej a wstrzykiwaniem przez setter (kod poniżej)?
Kiedy chcę skorzystać z settera?
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();
}
@Autowired
public void setCustomerRepository(CustomerRepository customerRepository) {
System.out.println("We are using setter injection");
this.customerRepository = customerRepository;
}
}