基於註解的IOC配置

用於創建對象的

它們的作用就和在xml配置文件中編寫一個<bean>標籤實現的功能一樣
	 @Component
     作用:用把當前類對象存入spring容器
     屬性:
     	value:用於指定bean的id。不寫時,它的默認值爲當前類目且首字母小寫
   		@Controller,一般用於表現層
  		@Service,一般用於業務層
 		@Repository,一般用於持久層
用於注入數據的
 它們的作用就和在xml配置文件中編寫一個<bean>標籤中寫一個<property>標籤實現的功能一樣的
  @Autowired
       作用:自動按照類型注入。只要容器中有唯一的bean對象類型和要注入的變量類型匹配,就可以注入成功
               		如果ioc容器中沒有任何bean的類型和要注入的變量類型匹配,則報錯
                  	如果ioc容器中有多個類型匹配時,會根據名稱來查找。
          出現位置:
               可以是成員,也可以是方法
           細節:set和get方法不是必須的
  @Qualifier :
        作用:在按照類中注入的基礎之上再按照名稱注入。他在給類成員注入時不能單獨使用。但是在給方法參數注入時可以
        屬性:
              value,用於指定注入bean的id
   @Resource:
           作用:直接按照bean的id注入。它可以單獨使用
            屬性:
                   name:用於指定bean的id
       以上三個注入都只能注入其它bean類型的數據,而基本類型和String類型無法使用上述註解實現。
       另外,集合類型的注入只能通過XML來實現

    @Value
          作用:用於注入基本類型和String類型的數據
           屬性:
              value:用於指定數據的值。它可以使用spring中SpEl(也就是spring的el 表達式)
                      SpEl 的寫法:$(表達式)

用於改變作用範圍的

   它們的作用就和在xml配置文件中編寫一個<bean>標籤中使用scop屬性實現的功能一樣的
   Scope
       作用:用於指定bean的作用範圍
       屬性:
           value:指定範圍的取值。常用取值:singleton 、prototype
           不寫的話默認單例

和生命週期相關的

   它們的作用就和在xml配置文件中編寫一個<bean>標籤中使用init-method和destroy-method的作用一樣的
   @PreDestroy
       作用:用於指定銷燬方法
   @PostConstruct
       作用:用於指定初始化方法

spring中的新註解

Configuration
   作用:指定該類是一個配置類,作用和bean.xml相等
ComponentScan
   作用:用於通過註解指定spring在創建容器時要掃描的包
   屬性:
       value:他和basePackage的作用一樣,都是用於指定創建容器時要掃描的包
               我們使用此註解就等同於在xml中配置了
               <context:component-scan base-package="mu.lin.hu"/>

Bean
   作用:用於把當前方法的返回值作爲bean對象存入spring的ioc容器
   屬性:
       name:用於指定Bean的id。當不寫時,默認值是當前方法的名稱
   細節:
       當我們使用註解配置方法時,如果方法有參數時,spring框架會去容器中查找有沒有可用的對象。
       查找方式和Autowired註解的作用時一樣
Import
   作用:用於導入其它配置類
 屬性:
      value:用於指定其它配置類的字節碼
               當我們使用Import的註解後,有Import註解的類就爲父配置類,其它爲子配置類
 PropertySource
       作用:用於指定properties文件的位置
       屬性:
           value:指定文件的名稱和路徑。
           關鍵字:classpath,表示類路徑下

一個完整的案例

package mu.lin.hu.dao;

import mu.lin.hu.domain.Account;

import java.util.List;

/**
 * 賬戶的持久層接口
 */
public interface IAccountDao {
    public List<Account> findAllAccount() ;

    public Account findById(Integer id) ;

    public void saveAccount(Account account) ;

    public void updateAccount(Account account) ;

    public void deleteAccount(Integer accountId);
}

package mu.lin.hu.dao.impl;

import mu.lin.hu.dao.IAccountDao;
import mu.lin.hu.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    private QueryRunner runner;

    public List<Account> findAllAccount() {
        List<Account> accountList=null;
        try {

            accountList= runner.query("select * from account",new BeanListHandler<Account>(Account.class));

        }catch (Exception e){
            e.printStackTrace();
        }
        return accountList;
    }

    public Account findById(Integer id) {
        Account account=null;
        try {
           account = runner.query("select id ,name,money from account where id=?",new BeanHandler<Account>(Account.class),id);
        }catch (Exception e){
            e.printStackTrace();
        }

        return account;
    }

    public void saveAccount(Account account) {

        try {
            runner.update("insert into account(name,money) values(?,?) ",account.getName(),account.getMoney());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void updateAccount(Account account) {
        try {
            runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void deleteAccount(Integer accountId) {
        try {
            runner.update("delete from  account where id=? ",accountId);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

package mu.lin.hu.domain;

import java.io.Serializable;

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 +
                '}';
    }
}

package mu.lin.hu.service;

import mu.lin.hu.domain.Account;

import java.util.List;

public interface IAccountService {
    /**
     * 查詢所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查詢一個
     * @return
     */
    Account findById(Integer id);

    void saveAccount(Account account);

    void updateAccount(Account account);

    void deleteAccount(Integer accountId);
}

package mu.lin.hu.service.impl;

import mu.lin.hu.dao.IAccountDao;
import mu.lin.hu.domain.Account;
import mu.lin.hu.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private IAccountDao accountDao;



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

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

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

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

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

package mu.lin.hu.config;


import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.*;

import javax.sql.DataSource;

/**
 * 該類是一個配置類
 * 作用和bean.xml相等
 * spring中的新註解
 * Configuration
 *      作用:指定該類是一個配置類
 *  ComponentScan
 *      作用:用於通過註解指定spring在創建容器時要掃描的包
 *      屬性:
 *          value:他和basePackage的作用一樣,都是用於指定創建容器時要掃描的包
 *                  我們使用此註解就等同於在xml中配置了
 *                  <context:component-scan base-package="mu.lin.hu"/>
 *
 *  Bean
 *      作用:用於把當前方法的返回值作爲bean對象存入spring的ioc容器
 *      屬性:
 *          name:用於指定Bean的id。當不寫時,默認值是當前方法的名稱
 *      細節:
 *          當我們使用註解配置方法時,如果方法有參數時,spring框架會去容器中查找有沒有可用的對象。
 *          查找方式和Autowired註解的作用時一樣
 *  Import
 *      作用:用於導入其它配置類
 *      屬性:
 *          value:用於指定其它配置類的字節碼
 *                  當我們使用Import的註解後,有Import註解的類就爲父配置類,其它爲子配置類
 *  PropertySource
 *          作用:用於指定properties文件的位置
 *          屬性:
 *              value:指定文件的名稱和路徑。
 *              關鍵字:classpath,表示類路徑下
 */
@Configuration
@ComponentScan(basePackages = "mu.lin.hu")
@Import({JdbcConfig.class})
public class SpringConfiguration {

    /**
     * 用於創建QueryRunner對象
     * @param dataSources
     * @return
     */
    @Bean(name = "runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource dataSources){
        return new QueryRunner(dataSources);
    }




}

package mu.lin.hu.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
@PropertySource("classpath:jdbcConfig.properties")
public class JdbcConfig {
    @Value("${jdbc.Driver}")
    private String driverClass;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    /**
     * 創建數據源對象
     * @return
     */
    @Bean
    public DataSource createDataSource(){
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        try {
            dataSource.setDriverClass(driverClass);
        }catch (Exception e){
            e.printStackTrace();
        }

        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}
配置文件的內容
jdbc.Driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springtest
jdbc.username=root
jdbc.password=root

測試
package mu.lin.hu.test;

import mu.lin.hu.config.SpringConfiguration;
import mu.lin.hu.domain.Account;
import mu.lin.hu.service.IAccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * 使用junit 單元測試
 * spring整合junit的配置
 *      1.導入spring整合junit的jar包 或座標
 *      2.使用junit提供的一個註解把原有的main方法替換了,替換成spring提供的
 *         @Runwith
 *      3.告知spring的運行容器,spring和ioc創建是基於xml還是註解的。並且說明位置
 *          @ContextConfiguration
 *                      locations:指定xml文件的位置,加上classpath關鍵字,表示在類路徑下
 *                      classes: 指定註解類所在地位置
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes =SpringConfiguration.class )
public class AccountServiceTest {
    @Autowired
    private IAccountService as;
    @Test
    public void testFindAll(){
        //ApplicationContext ac=new AnnotationConfigApplicationContext("mu.lin.hu");
        //ApplicationContext ac=new AnnotationConfigApplicationContext(SpringConfiguration.class);
       // IAccountService as=ac.getBean("accountService",IAccountService.class);
        List<Account> accounts=as.findAllAccount();
        for(Account account:accounts){
            System.out.println(account);
        }

    }
    @Test
    public void testFindone(){
        ApplicationContext ac=new AnnotationConfigApplicationContext(SpringConfiguration.class);
        IAccountService as=ac.getBean("accountService",IAccountService.class);
        Account account=as.findById(1);
        System.out.println(account);
    }
    @Test
    public void testSave(){
        Account account=new Account();
        account.setName("lin");
        account.setMoney(123.0f);
        ApplicationContext ac=new AnnotationConfigApplicationContext(SpringConfiguration.class);
        IAccountService as=ac.getBean("accountService",IAccountService.class);
        as.saveAccount(account);

    }
    @Test
    public void testUpdate(){
        ApplicationContext ac=new AnnotationConfigApplicationContext(SpringConfiguration.class);
        IAccountService as=ac.getBean("accountService",IAccountService.class);
        Account account=as.findById(4);
        account.setName("yong1");
        as.updateAccount(account);
    }
    @Test
    public void testdelete(){
        ApplicationContext ac=new AnnotationConfigApplicationContext(SpringConfiguration.class);
        IAccountService as=ac.getBean("accountService",IAccountService.class);
        as.deleteAccount(4);
    }
}

pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>mu.lin.hu</groupId>
    <artifactId>day02_eesy_04_accountannoioc_withoutXML</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.39</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
    </dependencies>

</project>

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章