JavaEE學習日誌(八十八): spring依賴注入

JavaEE學習日誌持續更新----> 必看!JavaEE學習路線(文章總彙)

Spring

依賴注入

構造方法注入

有一個User類

package com.itheima.domain;

import java.util.Date;

public class User {
    private Integer id;
    private String username;
    private Date birthday;
    private Character sex;

    public User(Integer id, String username) {
        this.id = id;
        this.username = username;
    }

    public User() {
    }

    public Integer getId() {
        return id;
    }

    public String getUsername() {
        return username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public Character getSex() {
        return sex;
    }
}

三種構造方法的注入方式:索引,參數類型和參數名稱
注意:使用索引方式注入時,如果有多個構造方法,可能會出現錯誤

<!--依賴注入-->
    <!--默認創建對象的方式,使用默認的空參構造創建對象-->
    <bean id="user" class="com.itheima.domain.User">
        <!--constructor-arg通過構造方法的索引賦值-->
<!--        <constructor-arg index="0" value="1"></constructor-arg>-->
<!--        <constructor-arg index="1" value="張三"></constructor-arg>-->
        <!--通過參數類型賦值-->
<!--        <constructor-arg type="java.lang.Integer" value="2"></constructor-arg>-->
<!--        <constructor-arg type="java.lang.String" value="李四"></constructor-arg>-->
        <!--通過構造方法參數的名字賦值-->
        <constructor-arg name="id" value="3"></constructor-arg>
        <constructor-arg name="username" value="王五"></constructor-arg>

    </bean>

測試類

@Test
    public void test3(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = ac.getBean("user", User.class);
        System.out.println(user.getId());
        System.out.println(user.getUsername());

    }

補充:

  • value屬性:只能賦值簡單類型
  • ref屬性:pojo類型,複雜類型,關聯創建好的對象
    如Date類型
<bean id="user" class="com.itheima.domain.User">
        <!--constructor-arg通過構造方法的索引賦值-->
<!--        <constructor-arg index="0" value="1"></constructor-arg>-->
<!--        <constructor-arg index="1" value="張三"></constructor-arg>-->
        <!--通過參數類型賦值-->
<!--        <constructor-arg type="java.lang.Integer" value="2"></constructor-arg>-->
<!--        <constructor-arg type="java.lang.String" value="李四"></constructor-arg>-->
        <!--通過構造方法參數的名字賦值-->
        <constructor-arg name="id" value="3"></constructor-arg>
        <constructor-arg name="username" value="王五"></constructor-arg>
        <constructor-arg name="sex" value=""></constructor-arg>
        <constructor-arg name="birthday" ref="birthday"></constructor-arg>
    </bean>
    <bean id="birthday" class="java.util.Date"></bean>

set方法注入屬性(常用)

property:屬性注入

<bean id="birthday" class="java.util.Date"></bean>
    <!--通過set方法注入-->
    <bean id="user2" class="com.itheima.domain.User">
        <!--property:屬性注入-->
        <property name="username" value="abc"></property>
        <property name="birthday" ref="birthday"></property>
        <property name="sex" value=""></property>
        <property name="id" value="4"></property>
    </bean>

p名稱空間注入

原理也是基於set方法,但無法注入集合

1、在頭部中引入p名稱空間:第三行

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

2、使用p名稱空間注入

<!--使用p名稱空間注入-->
    <bean id="user3" class="com.itheima.domain.User"
          p:id="5" p:username="abc" p:sex="" p:birthday-ref="birthday"
    >
    </bean>

注入集合屬性

一、User中添加集合屬性list,set和數組

private List<String> list;
private Set<String> set;
private String[] strs;

注意:array,list,set結構相同,標籤可以混用

<!--注入集合屬性-->
    <bean id="user4" class="com.itheima.domain.User">
        <!--array,list,set結構相同,標籤可以混用-->
        <property name="list">
            <list>
                <value>abc</value>
                <value>abcd</value>
                <value>abcde</value>
            </list>
        </property>
        <property name="set">
            <set>
                <value>222</value>
                <value>333</value>
                <value>444</value>
            </set>
        </property>
        <property name="strs">
            <array>
                <value>555</value>
                <value>666</value>
                <value>777</value>
            </array>
        </property>
    </bean>

二、User中添加map和properties

private Map<String,String> map;
private Properties properties;

注意:map和properties結構相同,可以混用

<!--map和properties結構相同,可以混用-->
    <bean id="user5" class="com.itheima.domain.User">
        <property name="map">
            <map>
                <!--鍵值對配置-->
                <entry key="1" value="aaa"></entry>
                <entry key="2" value="bbb"></entry>
                <entry key="3" value="ccc"></entry>
            </map>

        </property>
        <property name="properties">
            <props>
                <prop key="">ddd</prop>
                <prop key="">eee</prop>
            </props>
        </property>
    </bean>

springIOC完成賬戶表的CRUD

創建數據庫表

create table account(id int primary key auto_increment,name varchar(40),money float) character set utf8 collate utf8_general_ci;insert into account(name,money) values('aaa',1000);insert into account(name,money) values('bbb',1000);insert into account(name,money) values('ccc',1000);

AccountDaoImpl

package com.itheima.dao.impl;

import com.itheima.dao.AccountDao;
import com.itheima.domain.Account;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.beans.PropertyVetoException;
import java.sql.SQLException;
import java.util.List;


public class AccountDaoImpl implements AccountDao {
    QueryRunner qr;

    public void setQr(QueryRunner qr) {
        this.qr = qr;
    }

    @Override
    public List<Account> findAll() {
        String sql = "select * from account";
        try {
            List<Account> accountList = qr.query(sql, new BeanListHandler<Account>(Account.class));
            return accountList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Account findById(Integer id) {
        String sql = "select * from account where id = ?";
        try {
            return qr.query(sql,new BeanHandler<Account>(Account.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void save(Account account) {
        String sql = "insert into account values(null,?,?)";
        try {
            qr.update(sql,account.getName(),account.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void update(Account account) {
        String sql = "update account set name = ? , money = ? where id =?";
        try {
            qr.update(sql,account.getName(),account.getMoney(),account.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void del(Integer id) {
        String sql = "delete from account where id = ?";
        try {
            qr.update(sql, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

AccountServiceImpl

package com.itheima.service.impl;

import com.itheima.dao.AccountDao;
import com.itheima.dao.impl.AccountDaoImpl;
import com.itheima.domain.Account;
import com.itheima.service.AccountService;

import java.util.List;

public class AccountServiceImpl implements AccountService {
    //創建容器,使用依賴注入
    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public List<Account> findAll() {
        return accountDao.findAll();
    }

    @Override
    public Account findById(Integer id) {
        return accountDao.findById(id);
    }

    @Override
    public void save(Account account) {
        accountDao.save(account);
    }

    @Override
    public void update(Account account) {
        accountDao.update(account);
    }

    @Override
    public void del(Integer id) {
        accountDao.del(id);
    }
}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--創建AccountService對象:需要AccountDao對象,依賴注入dao對象-->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>
    <!--創建AccountDao對象,需要qr-->
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
        <!--通過set方法注入qr-->
        <property name="qr" ref="qr"></property>
    </bean>
    <!--創建qr對象,需要數據源對象,通過構造方法的參數類型注入-->
    <bean id="qr" class="org.apache.commons.dbutils.QueryRunner">
        <constructor-arg type="javax.sql.DataSource" ref="dataSource"></constructor-arg>
    </bean>
    <!--創建數據源對象:需要注入四個參數,通過set方法注入-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
</beans>

測試類:只測試一個findAll

@Test
    public void test(){
        //創建容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //創建service對象
        AccountService accountService = ac.getBean("accountService",AccountService.class);
        List<Account> accountList = accountService.findAll();
        for (Account account : accountList) {
            System.out.println(account);
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章