Spring

重點內(nèi)容IoC和AOP

Spring

Spring是分層的 Java SE/EE應(yīng)用 full-stack 輕量級開源框架作儿,以 IoC(Inverse Of Control:反轉(zhuǎn)控制)和 AOP(Aspect Oriented Programming:面向切面編程)為內(nèi)核伴逸,提供了展現(xiàn)層 SpringMVC 和持久層 Spring JDBC 以及業(yè)務(wù)層事務(wù)管理等眾多的企業(yè)級應(yīng)用技術(shù),還能整合開源世界眾多著名的第三方框架和類庫维蒙,逐漸成為使用最多的Java EE 企業(yè)應(yīng)用開源框架
spring 的體系結(jié)構(gòu)

編寫XML 配置spring賬戶轉(zhuǎn)賬案例
實體類Account .java

package com.neusoft.domain;

import java.io.Serializable;

/**
 * @author Eric Lee
 * @date 2020/9/5 11:01
 */
public class Account implements Serializable {
    private Integer id;
    private String name;
    private Float money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

Dao

package com.neusoft.dao;

import com.neusoft.domain.Account;

import java.util.List;

public interface IAccountDao {

    List<Account> findAllAccount();

    Account findAccountById(Integer accountId);

    void saveAccount(Account account);

    void updateAccount(Account account);

    void deleteAccount(Integer accountId);

}

impl

package com.neusoft.dao.Impl;

import com.neusoft.dao.IAccountDao;
import com.neusoft.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

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

/**
 * @author Eric Lee
 * @date 2020/9/5 11:10
 */
public class AccountDaoImpl  implements IAccountDao {

    private QueryRunner runner;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    @Override
    public List<Account> findAllAccount() {
        try {
            return runner.query("select * from account", new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findAccountById(Integer accountId) {
        try {
            return runner.query("select * from account where id = ?", new BeanHandler<Account>(Account.class), accountId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveAccount(Account account) {
        try {
            runner.update("insert into account(name,money) values (?, ?)",account.getName(), account.getMoney());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateAccount(Account account) {

        try {
            runner.update("update account set name= ? , money = ? where id=? ",account.getName(), account.getMoney(), account.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void deleteAccount(Integer accountId) {

        try {
            runner.update("delete from account where id = ?", accountId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
}

bean.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">
<!--    配置service-->
    <bean id="accountService" class="com.neusoft.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>
<!--    配置dao-->
    <bean id="accountDao" class="com.neusoft.dao.Impl.AccountDaoImpl">
<!--        注入qr-->
        <property name="runner" ref="runner"></property>
    </bean>

<!--    配置QueryRunner-->

    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner">
<!--        注入數(shù)據(jù)源-->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>

    <!--    配置數(shù)據(jù)源-->
    <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/java9_spring"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>

    </bean>

</beans>

service

package com.neusoft.service;

import com.neusoft.domain.Account;

import java.util.List;

public interface IAccountService {

    // 查詢所有
    List<Account> findAllAccount();

    Account findAccountById(Integer accountId);

    void  saveAccount(Account account);

    void  updateAccount(Account account);

    void deleteAccount(Integer accountId);

}

實現(xiàn)

package com.neusoft.service.impl;

import com.neusoft.dao.IAccountDao;
import com.neusoft.dao.Impl.AccountDaoImpl;
import com.neusoft.domain.Account;
import com.neusoft.service.IAccountService;

import java.util.List;

/**
 * @author Eric Lee
 * @date 2020/9/5 11:39
 */
public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao;

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

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

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

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

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

    @Override
    public void deleteAccount(Integer accountId) {
            accountDao.deleteAccount(accountId);
    }
}

Test

package com.neusoft.test;

import com.neusoft.domain.Account;
import com.neusoft.service.IAccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * @author Eric Lee
 * @date 2020/9/5 14:09
 */
public class TestAccountService {

    ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    IAccountService as = ac.getBean("accountService", IAccountService.class);

    @Test
    public void testFindAll() {

        //3.執(zhí)行方法
        List<Account> accounts = as.findAllAccount();
        for(Account account : accounts){
            System.out.println(account);
        }
    }

    @Test
    public void testFindOne() {
        //3.執(zhí)行方法
        Account account = as.findAccountById(1);
        System.out.println(account);
    }

    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("test");
        account.setMoney(12345f);
        //3.執(zhí)行方法
        as.saveAccount(account);

    }

    @Test
    public void testUpdate() {
        //3.執(zhí)行方法
        Account account = as.findAccountById(4);
        account.setMoney(23456f);
        as.updateAccount(account);
    }

    @Test
    public void testDelete() {
        //3.執(zhí)行方法
        as.deleteAccount(4);
    }
}

使用注解進行配置

bean.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"
       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.neusoft">

    </context:component-scan>
<!--    配置QueryRunner-->

    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner">
<!--        注入數(shù)據(jù)源-->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>

    <!--    配置數(shù)據(jù)源-->
    <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/java9_spring"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>

    </bean>

</beans>

核心修改
將對象交給spring去管理, 指定掃描的包名

 <context:component-scan base-package="com.neusoft">
 </context:component-scan>

service層

image

dao層

image

@Component

image
  • 作用
    把資源讓 spring 來管理果覆。相當于在 xml 中配置一個 bean颅痊。
  • 屬性
    value:指定 bean 的 id。如果不指定 value 屬性局待,默認 bean 的 id 是當前類的類名斑响。首字母小寫菱属。

@Controller @Service @Repository

他們?nèi)齻€注解都是針對一個的衍生注解,他們的作用及屬性都是一模一樣的舰罚。
他們只不過是提供了更加明確的語義化纽门。
@Controller :一般用于表現(xiàn)層的注解。
@Service :一般用于業(yè)務(wù)層的注解营罢。
@Repository :一般用于持久層的注解
細節(jié):如果注解中有且只有一個屬性 要賦值時是 赏陵,且名稱是 value ,value 在賦值是可以不寫

@Autowired

作用:自動按照類型注入饲漾。當使用注解注入屬性時蝙搔,set方法可以省略。它只能注入其他 bean 類型能颁。當有多個類型匹配時杂瘸,使用要注入的對象變量名稱作為 bean 的 id,在 spring 容器查找伙菊,找到了也可以注入成功败玉。找不到就報錯。
相當于: <property name="accountDao" ref="accountDao"></property>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末镜硕,一起剝皮案震驚了整個濱河市运翼,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌兴枯,老刑警劉巖血淌,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異财剖,居然都是意外死亡悠夯,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進店門躺坟,熙熙樓的掌柜王于貴愁眉苦臉地迎上來沦补,“玉大人,你說我怎么就攤上這事咪橙∠Π颍” “怎么了?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵美侦,是天一觀的道長产舞。 經(jīng)常有香客問我,道長菠剩,這世上最難降的妖魔是什么易猫? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮具壮,結(jié)果婚禮上擦囊,老公的妹妹穿的比我還像新娘违霞。我一直安慰自己,他們只是感情好瞬场,可當我...
    茶點故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布买鸽。 她就那樣靜靜地躺著,像睡著了一般贯被。 火紅的嫁衣襯著肌膚如雪眼五。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天彤灶,我揣著相機與錄音看幼,去河邊找鬼。 笑死幌陕,一個胖子當著我的面吹牛诵姜,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播搏熄,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼棚唆,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了心例?” 一聲冷哼從身側(cè)響起宵凌,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎止后,沒想到半個月后瞎惫,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡译株,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年瓜喇,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片歉糜。...
    茶點故事閱讀 39,981評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡乘寒,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出现恼,到底是詐尸還是另有隱情,我是刑警寧澤黍檩,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布叉袍,位于F島的核電站,受9級特大地震影響刽酱,放射性物質(zhì)發(fā)生泄漏喳逛。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一棵里、第九天 我趴在偏房一處隱蔽的房頂上張望润文。 院中可真熱鬧姐呐,春花似錦、人聲如沸典蝌。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽骏掀。三九已至鸠澈,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間截驮,已是汗流浹背笑陈。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留葵袭,地道東北人涵妥。 一個月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像坡锡,于是被迫代替她去往敵國和親蓬网。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,933評論 2 355