2.1 基于注解的IOC配置

导入jar包

bean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">
    
    <!-- 告知spring在创建容器时要扫描的包。当配置了此标签之后,spring创建容器就会去指定的包及其子包下找对应的注解
        标签是在一个context的名称空间里,所以必须先导入context名称空间
     -->
    <context:component-scan base-package="com.itheima"></context:component-scan>
    
</beans>

Client.java

package com.itheima.ui;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.itheima.service.ICustomerService;

public class Client {

    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        ICustomerService cs1 =(ICustomerService) ac.getBean("customerService");
//      System.out.println(cs);
//      cs.saveCustomer();
        
        ICustomerService cs2 =(ICustomerService) ac.getBean("customerService");
        System.out.println(cs1 == cs2);
    }

}

CustomerServiceImpl.java

package com.itheima.service.impl;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.itheima.dao.ICustomerDao;
import com.itheima.service.ICustomerService;

/**
 * 客户的业务层实现类
 * @author zhy
 * <bean id="customerService" class="com.itheima.service.impl.CustomerServiceImpl"></bean>
 * 1、用于创建bean对象
 *      @Component
 *          作用:就相当于配置了一个bean标签。
 *          它能出现的位置:类上面
 *          属性:value。含义是指定bean的id。当不写时,它有默认值,默认值是:当前类的短名首字母改小写。
 *      由此注解衍生的三个注解:
 *          @Controller     一般用于表现的注解   
 *          @Service        一般用于业务层
 *          @Repository     一般用于持久层
 *          他们和@Component的作用及属性都是一模一样
 * 2、用于注入数据的
 *      @Autowired
 *          作用:自动按照类型注入。只要有唯一的类型匹配就能注入成功。
 *              如果注入的bean在容器中类型不唯一时,它会把变量名称作为bean的id,在容器中查找,找到后也能注入成功。
 *              如果没有找到一致的bean的id,则报错。
 *               当我们使用注解注入时,set方法就不是必须的了。
 *      @Qualifier
 *          作用:在自动按照类型注入的基础之上,再按照bean的id注入。它在给类成员注入数据时,不能独立使用。但是再给方法的形参注入数据时,可以独立使用。
 *          属性:
 *              value:用于指定bean的id。
 *      @Resource
 *          作用:直接按照bean的id注入。
 *          属性:
 *              name:用于指定bean的id。
 *      以上三个注解都是用于注入其他bean类型的。用于注入基本类型和String类型需要使用Value
 *      @Value:
 *          作用:用于注入基本类型和String类型数据。它可以借助spring的el表达式读取properties文件中的配置。
 *          属性:
 *              value:用于指定要注入的数据
 * 3、用于改变作用范围的
 *      @Scope
 *          作用:用于改变bean的作用范围
 *          属性:
 *           value:用于指定范围的取值。
 *           取值和xml中scope属性的取值是一样的。singleton prototype request session globalsession
 * 4、和生命周期相关的
 * 5、spring的新注解
 * 
 */
@Service("customerService")
@Scope("prototype")
public class CustomerServiceImpl implements ICustomerService {

    @Value("泰斯特")
    private String name;
    
//  @Autowired
//  @Qualifier("customerDao1")
    @Resource(name="customerDao2")
    private ICustomerDao customerDao = null;    
    

    @Override
    public void saveCustomer() {
        System.out.println("业务层调用持久层......"+name);
        customerDao.saveCustomer();
    }

}

xml方式可以避免修改源码,重启服务器,但是繁琐,文件过多,不好维护。
需要经常修改就选xml

修改项目

JdbcConfig.java

package config;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * Jdbc的配置类
 * @author zhy
 *
 */
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;

    @Bean(name="runner")//它是把方法的返回值存入spring容器中。该注解有一个属性,name:用于指定bean的id。当不指定时它有默认值,默认值是方法的名称。
    public QueryRunner createQueryRunner(@Qualifier("ds1")DataSource dataSource){
        return new QueryRunner(dataSource);
    }
    
    @Bean(name="ds")
    public DataSource createDataSource(){
        try {
            System.out.println(driver);//com.mysql.jdbc.Driver  
            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 {
            System.out.println(url);
            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);
        }
    }
}

SpringConfiguration.java

package config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

/**
 * 一个spring的配置类
 *  它的作用就相当于bean.xml
 * @author zhy
 */
//commonent如果需要用类的对象,让spring管理,就配置,不然import就可以,避免占用容器内存
@Configuration//它就是把当前类看成是spring的配置类,用处不大,注解后不必写路径就可以找到
@ComponentScan({"com.itheima"})//配置要扫描的包
@Import({JdbcConfig.class})//导入其他配置类
@PropertySource("classpath:config/jdbcConfig.properties")
public class SpringConfiguration {
    
    @Bean//把方法的返回值存入spring容器中该注解有一个属性,name:用于指定bean的id,默认值是方法的名称
    public static PropertySourcesPlaceholderConfigurer createPropertySourcesPlaceholderConfigurer(){
        return  new PropertySourcesPlaceholderConfigurer();
    }
}

jdbcConfig.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/day64_spring01
jdbc.username=root
jdbc.password=suntong

CustomerServiceImpl.java

package com.itheima.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;

import com.itheima.dao.ICustomerDao;
import com.itheima.domain.Customer;
import com.itheima.service.ICustomerService;
/**
 * 客户的业务层实现类
 * @author zhy
 *
 */
@Service("customerService")
public class CustomerServiceImpl implements ICustomerService {

    @Resource(name="customerDao")
    private ICustomerDao customerDao ;
    

    @Override
    public List<Customer> findAllCustomer() {
        return customerDao.findAllCustomer();
    }

    @Override
    public void saveCustomer(Customer customer) {
        customerDao.saveCustomer(customer);
    }

    @Override
    public void updateCustomer(Customer customer) {
        customerDao.updateCustomer(customer);
    }

    @Override
    public void deleteCustomer(Long custId) {
        customerDao.deleteCustomer(custId);
    }

    @Override
    public Customer findCustomerById(Long custId) {
        return customerDao.findCustomerById(custId);
    }

}

CustomerDaoImpl.java

package com.itheima.dao.impl;

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

import javax.annotation.Resource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.stereotype.Repository;

import com.itheima.dao.ICustomerDao;
import com.itheima.domain.Customer;
/**
 * 客户的持久层实现类
 * @author zhy
 *
 */
@Repository("customerDao")
public class CustomerDaoImpl implements ICustomerDao {

    @Resource(name="runner")
    private QueryRunner runner ;
    

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

    @Override
    public void saveCustomer(Customer customer) {
        try {
            runner.update("insert into cst_customer(cust_name,cust_source,cust_industry,cust_level,cust_address,cust_phone)values(?,?,?,?,?,?)",
                    customer.getCust_name(),customer.getCust_source(),customer.getCust_industry(),
                    customer.getCust_level(),customer.getCust_address(),customer.getCust_phone());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateCustomer(Customer customer) {
        try {
            runner.update("update cst_customer set cust_name=?,cust_source=?,cust_industry=?,cust_level=?,cust_address=?,cust_phone=?  where cust_id=?",
                    customer.getCust_name(),customer.getCust_source(),customer.getCust_industry(),
                    customer.getCust_level(),customer.getCust_address(),customer.getCust_phone(),customer.getCust_id());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteCustomer(Long custId) {
        try {
            runner.update("delete from cst_customer where cust_id = ? ",custId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Customer findCustomerById(Long custId) {
        try {
            return runner.query("select * from cst_customer where cust_id = ? ",new BeanHandler<Customer>(Customer.class),custId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}

CustomerServiceTest.java

package com.itheima.test;

import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.itheima.domain.Customer;
import com.itheima.service.ICustomerService;

import config.SpringConfiguration;
/**
 * 测试客户的业务层
 * @author zhy
 *
 */
public class CustomerServiceTest {

    @Test
    public void testFindAllCustomer() {
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        ICustomerService cs = (ICustomerService) ac.getBean("customerService");
        List<Customer> list = cs.findAllCustomer();
        for(Customer c : list){
            System.out.println(c);
        }
    }

    @Test
    public void testSaveCustomer() {
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        ICustomerService cs = (ICustomerService) ac.getBean("customerService");
        Customer c = new Customer();
        c.setCust_name("dbutils customer annotation");
        cs.saveCustomer(c);
    }

    @Test
    public void testUpdateCustomer() {
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        ICustomerService cs = (ICustomerService) ac.getBean("customerService");
        Customer c = cs.findCustomerById(94L);
        c.setCust_address("北京市顺义区");
        cs.updateCustomer(c);
    }

    @Test
    public void testDeleteCustomer() {
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        ICustomerService cs = (ICustomerService) ac.getBean("customerService");
    }

    @Test
    public void testFindCustomerById() {
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        ICustomerService cs = (ICustomerService) ac.getBean("customerService");
    }

}

五个新注解都在项目中包含了

全是注解并不爽,如果用xml,新注解都不用,主要resource和component。

Spring整合junit

  1. 拷贝spring提供的整合jar包
    spring-test-4.2.4.RELEASE.jar
  2. 使用junit提供的一个注解,把原有的main函数替换掉,换成Spring提供的
    @RunWith
    更换的类:SpringJunit4ClassRunner
  3. 使用Spring提供的注解告知Spring,配置文件或者注解类所在的位置
    @ContextConfiguration
package com.itheima.test;

import java.util.List;

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 com.itheima.domain.Customer;
import com.itheima.service.ICustomerService;

import config.SpringConfiguration;
/**
 * 测试客户的业务层
 * @author zhy
 * spring整合junit
 *  第一步:拷贝spring提供的整合jar包
 *      spring-test-4.2.4.RELEASE.jar
 *  第二步:使用junit提供的一个注解,把原有的main函数替换掉,换成spring提供的
 *      @RunWith
 *      要换的类:SpringJunit4ClassRunner
 *  第三步:使用spring提供的的注解告知spring,配置文件或者注解类所在的位置
 *      @ContextConfiguration
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={SpringConfiguration.class})
public class CustomerServiceTest {

    @Autowired
    private ICustomerService cs = null;
    
    @Test
    public void testFindAllCustomer() { 
        List<Customer> list = cs.findAllCustomer();
        for(Customer c : list){
            System.out.println(c);
        }
    }

    @Test
    public void testSaveCustomer() {
        Customer c = new Customer();
        c.setCust_name("dbutils customer annotation");
        cs.saveCustomer(c);
    }

    @Test
    public void testUpdateCustomer() {
        Customer c = cs.findCustomerById(94L);
        c.setCust_address("北京市顺义区");
        cs.updateCustomer(c);
    }

    @Test
    public void testDeleteCustomer() {
        cs.deleteCustomer(95L);
    }

    @Test
    public void testFindCustomerById() {
        Customer c = cs.findCustomerById(94L);
        System.out.println(c);
    }

}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,695评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,569评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,130评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,648评论 1 297
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,655评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,268评论 1 309
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,835评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,740评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,286评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,375评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,505评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,185评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,873评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,357评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,466评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,921评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,515评论 2 359

推荐阅读更多精彩内容