Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Autowire Fundamentals

Tags:

spring

I am a newbie in Spring and am trying to understand the below concept.

Assume that accountDAO is a dependency of AccountService.

Scenario 1:

<bean id="accServiceRef" class="com.service.AccountService">
    <property name="accountDAO " ref="accDAORef"/>
</bean>

<bean id="accDAORef" class="com.dao.AccountDAO"/>

Scenario 2:

<bean id="accServiceRef" class="com.service.AccountService" autowire="byName"/>
<bean id="accDAORef" class="com.dao.AccountDAO"/>

In AccountService Class:

public class AccountService {
    AccountDAO accountDAO;
    ....
    ....
}

In the second scenario, How is the dependency injected ? When we say it is autowired by Name , how exactly is it being done. Which name is matched while injecing the dependency?

Thanks in advance!

like image 498
MAlex Avatar asked Jul 06 '11 10:07

MAlex


1 Answers

Use @Component and @Autowire, it's the Spring 3.0 way

@Component
public class AccountService {
    @Autowired
    private AccountDAO accountDAO;
    /* ... */
}   

Put a component scan in your app context rather than declare the beans directly.

<?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:component-scan base-package="com"/>

</beans>
like image 184
Paul McKenzie Avatar answered Nov 12 '22 17:11

Paul McKenzie