1. 程式人生 > >Spring筆記-set物件注入與註解

Spring筆記-set物件注入與註解

一、set物件注入
一個物件的成員變數中常常含另一個類,這個時候就需要物件注入。

一個set注入的例子:
AccountServiceImpl類中成員變數含有AccountDao

AccountServiceImpl:

package zk;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.TransactionStatus;
import
org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionTemplate; public class AccountServiceImpl implements AccountService { /* * @Autowired * * @Qualifier("accountDao") */ **private AccountDao accountDao; public
void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; }** public void transfer(String from, String to, Double money) { accountDao.from(from, money); accountDao.in(to, money); } }

AccountDao類:
這個類不用太關心大概看一下就是

package zk;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

public
class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{ public void from(String from, Double money) { // TODO Auto-generated method stub String sql = "update account set money=money-? where name = ?"; this.getJdbcTemplate().update(sql,money,from); // System.out.println("adsasd"); } public void in(String in, Double money) { // TODO Auto-generated method stub String sql = "update account set money=money+? where name = ?"; this.getJdbcTemplate().update(sql, money,in); } }

配置applicationContext.xml

<bean id="accountDao" class="zk.AccountDaoImpl">
        <property name="dataSource" ref="dataSource" />
</bean>

<bean id="accountService" class="zk.AccountServiceImpl">
    <property name="accountDao" ref="accountDao"></property>
</bean>

setter注入物件有兩點需要注意:
1.需要在含有物件成員變數的那個類中提供被注入物件的set方法,就像這裡的AccountServiceImpl類 上面程式碼出現加粗的地方 就是物件成員變數與set方法
2.就是需要在applicationContext.xml中配置AccountServiceImpl類和AccountDaoImpl類,並且在AccountServiceImpl類中 配置成員變數 ref而不是value 這個不要搞錯了。

二、註解方式注入
跟上面的set方式注入不同的是,這裡不需要set方法了 AccountServiceImpl換成了如下:

package zk;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

public class AccountServiceImpl implements AccountService {

    @Autowired
    @Qualifier("accountDao")
    private AccountDao accountDao;

    public void transfer(String from, String to, Double money) {

        accountDao.from(from, money);
        accountDao.in(to, money);

    }

}

配置檔案如下:

<bean id="accountDao" class="zk.AccountDaoImpl">
        <property name="dataSource" ref="dataSource" />
</bean>
<bean id="accountService" class="zk.AccountServiceImpl">
        <!-- <property name="accountDao" ref="accountDao"></property> -->
</bean>

注意到 這裡不再需要,因此註釋掉了。

@Qualifier(“accountDao”) 這裡的”accountDao” 對應配置檔案中的AccountDao類的id。