【Spring】新注解

新注解

注解释意
@Configuration作用:指定当前类是一个配置类
细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写
 
@ComponentScan作用:用于通过注解指定Spring在创建容器时要扫描的包
属性:
          value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包
          使用此注解就等同于在xml中配置了:
          <content:component-scan base-package=“com.itheima”></content:component-scan>
@Bean作用:用于把方法的返回值作为bean对象存入spring的ioc容器中
属性:
          name:用于指定bean的id。当不写时,默认值是当前方法的名称
细节:
         当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象。
         查找的方式和Autowired注解的作用是一样的
@Import作用:用于导入其他配置类
属性:
         用于指定其他配置类的字节码
         当我们使用Import的注解后,有Import注解的类就是父配置类,而导入的都是子配置类
@PropertySource作用:用于指定properties文件的位置
属性:
          value:指定文件的名称和路径
                    关键字:classpath,表示类路径下

项目结构:
在这里插入图片描述
SpringConfiguration:该类是一个配置类,它的作用和bean.xml是一样的

@ComponentScan("com.itheima")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
}

jdbcConfig:数据源配置类,可配置多数据源

package config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
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 org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

//@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;


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

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name="ds1")
    public DataSource  createDataSource()  {
        ComboPooledDataSource ds= new ComboPooledDataSource();
        try {
            ds.setDriverClass(driver);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        ds.setJdbcUrl(url);
        ds.setUser(username);
        ds.setPassword(password);
        return ds;
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name="ds")
    public DataSource  createDataSource1()  {
        ComboPooledDataSource ds= new ComboPooledDataSource();
        try {
            ds.setDriverClass(driver);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesy02");
        ds.setUser(username);
        ds.setPassword(password);
        return ds;
    }
}

bean.xml配置文件被注解取代
jdbcConfig.properties:数据源配置类,用于将代码中写死的数据源连接取代掉

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

Spring整合Jnit

使用Junited单元测试,测试我们的配置

  1. 应用程序的入口
    main方法
  2. junit单元测试中,没有main方法也能执行
    junit集成了一个main方法
    该方法就会判断当前测试类中哪些方法有@Test注解
    junit就让有Test注解的方法执行
  3. junit不会管我们是否采用spring框架
    在执行测试方法时,junit根本不知道我们是不是使用了Spring框架
    所以也就不会为我们读取配置文件/配置类创建Spring核心容器
  4. 由以上三点可知
    当测试方法执行时,没有IOC容器,就算写了AutoWired注解,也无法实现注入
  5. Spring整合junit的配置
    1. 导入spring整合junit的jar(坐标)
    2. 使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的
      @Runwith
    3. 告知Spring的运行器,Spring和ioc创建基于xml还是注解的,并且说明位置
      @contextConfiguration
      Locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
      classes:指定注解类所在的位置
      当我们使用spring 5.x版本的时候,要求junit的jar必须是4.12及以上
package com.itheima.test;


import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.junit.runner.RunWith;
import org.junit.Test;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import config.SpringConfiguration;

import org.springframework.beans.factory.annotation.Autowired;


import java.util.List;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
//@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {

    @Autowired
    private IAccountService as;

    /*@Before
    public void init(){
        //1. 获取容器
        //ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
         ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //2. 得到业务层对象
         as=ac.getBean("accountService",IAccountService.class);
    }*/

    @Test
    public void testFindAll() {

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

    @Test
    public void testFindOne() {

        //3. 执行方法
        Account account=as.findAccountById(1);
    }

    @Test
    public void testSave() {
        Account account=new Account();
        account.setName("zhaofen**");
        account.setMoney(200f);

        //3. 执行方法
        as.saveAccount(account);

    }

    @Test
    public void testUpdate() {

        //3. 执行方法
        Account account=as.findAccountById(4);
        account.setName("test");
        as.updateAccount(account);
    }

    @Test
    public void testDelete() {

        //3. 执行方法
        as.deleteAccount(4);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值