Spring Autowire Fundamentals

后端 未结 2 2059
南笙
南笙 2021-02-09 07:32

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

Assume that accountDAO is a dependency of AccountService.

Scenar

相关标签:
2条回答
  • 2021-02-09 08:21
    <bean id="accServiceRef" class="com.service.accountService" autowire="byName">
    </bean>    
    <bean id="accDAORef" class="com.dao.accountDAO">
    </bean>
    

    and

    public class AccountService {
        AccountDAO accountDAO;
        /* more stuff */
    }
    

    When spring finds the autowire property inside accServiceRef bean, it will scan the instance variables inside the AccountService class for a matching name. If any of the instance variable name matches the bean name in the xml file, that bean will be injected into the AccountService class. In this case, a match is found for accountDAO.

    Hope it makes sense.

    0 讨论(0)
  • 2021-02-09 08:30

    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>
    
    0 讨论(0)
提交回复
热议问题