天天看點

spring第二天---spring基于注解的IOC以及Ioc的案例

Spring 第二天—spring基于注解的IOC以及Ioc的案例

文章目錄

    • Spring 第二天---spring基于注解的IOC以及Ioc的案例
      • 1.1 xml配置對應的注解
      • 1.2 基于xml的IOC
      • 1.3 改為注解配置--注解IOC
        • 1.3.1 Qulifier注解的另一種用法
      • 1.4 spring整個junit

1.1 xml配置對應的注解

注解bean.xml名稱空間與xml注入形式不一樣,需xmlns:context

/**
 * 賬戶的業務層實作類
 * 曾經xml的配置
 * <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"
 *  scope="" init-method="" destroy-method="">
 *      <property name="" value="" | ref=""></property>
 *  </bean>
 *
 * 用于建立對象的
 *      他們的作用就和在xml配置檔案中編寫一個<bean>标簽實作的功能是一樣的
 *      Component:
 *      作用:用于把目前類對象存入spring容器中
 *      屬性:
 *          value:用于指定bean的id。當我們不寫時,它的預設值是目前類名,且首字母小寫。
 *      Controller:一般用在表現層
 *      Service:一般用在業務層
 *      Repository:一般用在持久層
 *      以上三個注解他們的作用和屬性與Component是一模一樣。
 *      他們三個是spring架構為我們提供明确的三層使用的注解,是我們三層對象更加清晰。
 *
 * 用于注入資料的
 *      他們的作用就和在xml配置檔案中的bean标簽中寫一個<property>标簽的作用是一樣的
 *      Autowired:
 *          作用:自動按照類型注入。隻要容器中有唯一的一個bean對象類型和要注入的變量類型比對,就可以注入成功。
 *               用圖示範了一遍,如何自動注入,是看資料類型IAccountDao與@Repository("accountDao")dao層的實作一樣。(不是隻看實作類,實作類能看成接口也可以。)
 *               如果ioc容器中沒有任何bean的類型和要注入的變量類型比對,則報錯。
 *               如果ioc容器中有多個類型比對時:它會先根據資料類型找到要注入的範圍,然後再根據變量名去比對容器中的key,一緻則注入成功,否則報錯。
 *               @Autowired
 *               private IAccountDao accountDao1 = null;    dao層: @Repository("accountDao1")
 *          出現位置:
 *              可以是變量上,也可以是方法上
 *           細節:
 *              使用注解注入時,set方法就不是必需的了。
 *      Qualifier:
 *          作用:在按照類中注入的基礎之上再按照名稱注入。它在給類成員注入時不能單獨使用,但是在給方法參數注入時可以(稍後講)
 *                類成員時,要和Autowire配合使用
 *          示例:
 *              @Autowired
 *              @Qualifier("accountDao1")
 *              private IAccountDao accountDao = null;
 *          屬性:
 *              value:用于指定注入bean的id
 *      Resource
 *          作用:直接按照bean的id注入。它可以獨立使用
 *          屬性:
 *              name: 用于指定bean的id
 *      以上三個注入都隻能注入其他bean類型的資料,而基本類型和String類型無法使用上述注解實作。
 *      另外,集合類型的注入隻能通過xml實作
 *
 *      Value
 *          作用:用于注入基本類型和String類型的資料
 *          屬性:
 *              value:用于指定資料的值。它可以使用spring中SpEL(也就是spring的el表達式)
 *                      SpEL的寫法: ${表達式} 出現在哪就是哪個的
 *
 * 用于改變作用範圍的
 *      他們的作用就和在bean标簽中使用scope屬性實作的功能是一樣的。
 *      Scope
 *          作用:用于指定bean的作用範圍
 *          屬性:
 *              value: 指定範圍的取值。常用取值:singleton  prototype  不寫預設單例
 * 和生命周期相關  (了解)
 *      他們的作用就和bean标簽中使用init-method和destroy-method的作用是一樣的。
 *      PreDestory
 *          作用:用于指定銷毀方法
 *      PostConstruct
 *          作用:用于指定初始化方法
 *
 */
@Service(value = "accountService")
//@Scope("prototype")
public class AccountServiceImpl implements IAccountService {


//    @Autowired
//    @Qualifier("accountDao1")
    @Resource(name = "accountDao1")
    private IAccountDao accountDao = null;   //這個就是需要避免的 new

    public void saveAccount() {
        accountDao.saveAccount();

    }

    @PostConstruct
    public void init() {
        System.out.println("初始化方法執行了");

    }

    @PreDestroy
    public void destory() {
        System.out.println("銷毀方法執行了");
    }
}
           

1.2 基于xml的IOC

然後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.itheima.service.impl.AccountServiceImpl">
        <!-- 注入dao-->
        <property name="accountDao" ref="accountDao"></property>
    </bean>
    <!--配置Dao對象-->
    <bean id="accountDao" class="com.itheima.dao.impl.AccoutDaoImpl">
        <!--注入QueryRunner-->
        <property name="runner" ref="runner"></property>
    </bean>

    <!--配置QueryRunner,配成多例形式!!!!-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入資料源-->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>

    <!--配置資料源-->
    <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/eesy"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>

    </bean>
</beans>

           

1.3 改為注解配置–注解IOC

先是用之前學的幾種注解改造了xml形式。之後将其他的所有也改為了注解,增加了幾種新的注解。

三種方式:

  • 純xml 也不是很好,注入時還需要set方法
  • 半xml半注解 這種如果預設構造函數建立對象推薦xml形式(jar裡的),自己寫的類用注解,這種最好。
  • 純注解 也麻煩

新的注解:

/**
 * @author Ven
 * @version 1.0 2020/12/8
 *
 * 該類是一個配置類,它的作用和bean.xml是一樣的
 * spring中的新注解
 * Configuration
 *      作用:指定目前類是一個配置類
 *      細節:當配置類作為AnnotitionConfigApplicationContext對象建立的參數時,該注解可以不寫。
 * ComponentScan
 *      作用:用于通過注解指定spring在建立容器時要掃描的包
 *      屬性:
 *          value:它和basePackage的作用是一樣的,都是用于指定建立容器時要掃描的包
 *          我們使用此注解就等同于在xml中配置了:
 *              <context:component-scan base-package="com.itheima"></context:component-scan>
 * Bean
 *      作用:用于把目前方法的傳回值作為bean對象存入spring的ioc容器中
 *      屬性:
 *          name:用于指定bean的id。當不寫時,預設值是目前方法的名稱
 *      細節:
 *          當我們使用注解配置方法時,如果方法有參數,spring架構會去容器中查找有沒有可用的bean對象
 *          查找的方式和Autowired注解的作用是一樣的。
 * Import
 *      作用;用于導入其他的配置類
 *      屬性:
 *          value:用于指定其他配置類的位元組碼。
 *                  當我們使用Import的注解之後,有Import注解的類就是父配置類,而導入的都是子配置類
 * PropertySource
 *      作用:用于指定Properties檔案的位置
 *      屬性:
 *          value: 指定檔案的名稱和路徑
 *              關鍵字:classpath,表示類路徑下
 */
//@Configuration
@ComponentScan("com.itheima")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
    
}
           
/**
 * @author Ven
 * @version 1.0 2020/12/8
 * 和spring連接配接資料庫相關的配置類
 */
//@Configuration
public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    /**
     * 用于建立一個QueryRunner對象
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 建立資料源對象
     * @return
     */
    @Bean(name = "dataSource")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

           

1.3.1 Qulifier注解的另一種用法

直接用于形參,解決同一個類型比對多個對象、且容器bean id與形參比對不上的問題(Autowired比對機制)。

@Bean(name = "runner")
@Scope("prototype")
public QueryRunner createQueryRunner(@Qualifier("ds2") DataSource dataSource){
    return new QueryRunner(dataSource);
}

@Bean(name = "ds2")
public DataSource createDataSource(){
    try {
        ComboPooledDataSource ds = new ComboPooledDataSource();
        ds.setDriverClass(driver);
        ds.setJdbcUrl(url);
        ds.setUser(username);
        ds.setPassword(password);
        return ds;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

@Bean(name = "ds1")
public DataSource createDataSource1(){
    try {
        ComboPooledDataSource ds = new ComboPooledDataSource();
        ds.setDriverClass(driver);
        ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesy02");
        ds.setUser(username);
        ds.setPassword(password);
        return ds;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
           

1.4 spring整個junit

  • 1、應用程式的入口

    main方法

  • 2、junit單元測試中,沒有main方法也能執行

    junit內建了一個main方法

    該方法就會判斷目前測試類中哪些方法有 @Test注解

    junit就讓有Test注解的方法執行

  • 3、junit不會管我們是否采用spring架構

    在執行測試方法時,junit根本不知道我們是不是使用了spring架構

    是以也就不會為我們讀取配置檔案/配置類建立spring核心容器

  • 4、由以上三點可知

    當測試方法執行時,沒有Ioc容器,就算寫了Autowired注解,也無法實作注入

/**
 * 使用Junit單元測試:測試我們的配置
 * Spring整合junit的配置
 *      1、導入spring整合junit的jar包
 *      2、 使用junit提供的一個注解把原有的main方法替換了,替換成spring提供的
 *           @RunWith
 *      3、 告知spring的運作器,spring的ioc建立是基于xml還是注解的,并且說明位置
 *          @ContextConfiguration
 *              locations: 指定xml檔案的位置,加上classpath關鍵字,表示在類路徑下
 *              classes:指定注解類所在位置
 *   當我們使用spring5.x版本的時候,要求junit的jar包必須4.12及以上
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
//@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {

    @Autowired
    private IAccountService as;

    @Test
    public void testFindAll() {

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

asspath:bean.xml")
public class AccountServiceTest {

    @Autowired
    private IAccountService as;

    @Test
    public void testFindAll() {

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