spring Java AutoWiring
Jun 9, 2014 00:00 · 260 words · 2 minute read
You can automatically wiring interfaces with their implementation with java annotation in Spring. This way of auto wiring giving you a better understanding of how beans are wired together.
Wiring beans in configs
appConfig
@Configuration
@ComponentScan({"com.inadram"})
public class AppConfig {
@Bean(name = "customerService")
public CustomerService getCustomerService() {
return new CustomerServiceImplementation();
}
@Bean(name = "customerRepository")
public CustomerRepository getCustomerRepository() {
return new hibernateRepositoryImplementation();
}
}
@ComponentScan Add it to top of your configuration file to mark the start point of your app for looking for the beans.
@Bean
Mark the beans as auto wired. It can be mark by name or by type.
Setup classes to use config
by Adding Autowire annotation on top of the each instance it will map to the bean which define in the config.
Private member
you can set a private member as Autowire.
customerService
public class CustomerServiceImplementation implements CustomerService {
@Autowired
private CustomerRepository customerRepository ;
@Override
public List<Customer> findAll() {
return customerRepository.findAll();
}
}
use setter injection or constructor
Also you can use setter injection or constructor as Autowire
setter injection
public class CustomerServiceImplementation implements CustomerService {
@Autowired
public void setCustomerRepository(CustomerRepository customerRepository) {
System.out.println("setter injection");
this.customerRepository = customerRepository;
}
private CustomerRepository customerRepository ;
@Override
public List<Customer> findAll() {
return customerRepository.findAll();
}
}
using it
using it is pretty much similar to past.
application
public static void main(String[] args) {
ApplicationContext appContext = new AnnotationConfigApplicationContext(AppConfig.class);
CustomerService service = appContext.getBean("customerService", CustomerService.class);
System.out.println(service.findAll().get(0).getFirstName());
}
load the config and find bean that you wish to using it .
Download
feel free to download the full source code from my github.