componentscan注解的用法和作用_Spring新注解及Spring整合junit

@Configuration

  • 作用:指定当前类是一个配置类,等同于bean.xml

  • 细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写,这时系统将直接扫描该配置类。

//1.获取容器ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//AnnotationConfigApplicationContext     被springConfiguration注解过的类        /**         *     public AnnotationConfigApplicationContext(Class>... annotatedClasses) {         *         this();         *         this.register(annotatedClasses);         *         this.refresh();         *     }         */

@ComponentScan

  • 作用:用于通过注解指定spring在创建容器时要扫描的包

  • 属性:value,basePackages(两个属性别名互相引用,所以作用相同)指定要扫描的包

使用注解@ComponentScan(basePackages = {"com.itheima"})作用就等同于在xml中配置了

@Bean

  • 作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中

  • 属性:name:用于指定bean的id,当不写时,默认值是当前方法的名称

  • 细节:当使用注解配置方法时,如果方法有参数,spring会去容器中查找有没有可用的bean对象。查找的方式和Autowired相同,根据类型匹配,有一个注入成功,没有注入失败,有多个会找bean的id和该参数名相同的进行匹配,如果有多个,可以在参数前使用@Qualifier("")注解指定容器中的bean(单独使用的情况)。

@Import

  • 作用:导入其他的配置类。

  • 属性:value:指定其他配置类的字节码。 

  使用方法:@Import(xxxx.class) //xxxx为导入的配置类名

  使用了Import注解后,有Import注解的为父配置类,而导入的都是子配置类。

@PropertySource  

  • 作用:用于指定properties文件的位置

  • 属性:value:指定文件的名称和路径

  • 关键字:classpath:表示类路径下

简单例子

abb1a318a6d376db79fab28bea74384b.png

父配置类

//@Configuration//@ComponentScan(basePackages = "com.itheima")//@ComponentScan(basePackages = {"com.itheima"})//数组类型String[]//@ComponentScan({"com.itheima","config"})@ComponentScan("com.itheima")@Import(JdbcConfig.class)//classpath:表示后面的路径是一个类路径,指引jdbcConfig.properties加载//@PropertySource("classpath:com/itheima/jdbcConfig.properties")// 有包可以写classpath:com/itheima/jdbcConfig.properties 没包直接文件名写即可@PropertySource("classpath:jdbcConfig.properties")public class SpringConfiguration {}

子配置类

/** * 和spring连接数据库相关的配置类 *///@Configurationpublic class JdbcConfig {    //spring的el表达式${}    @Value("${jdbc.driver}") //jdbc.driver表示.properties中的key,等着spring给我们获取出value    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);        }    }}

jdbcConfig.properties

jdbc.driver=com.mysql.cj.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/eesy_spring?serverTimezone=UTCjdbc.username=rootjdbc.password=123456

测试类

public class AccountServiceTest {    @Autowired    private IAccountService as = null; @Test    public void testFindOne() {      //1.获取容器        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);        //2.得到业务层对象        IAccountService as = ac.getBean("accountService",IAccountService.class);        //3.执行方法        Account account = as.findAccountById(1);        System.out.println(account);    } }

运行结果

4f281c379601aec921a29cb571d5fabe.png

Spring整合junit配置

使用Junit单元测试:测试我们的配置

使用步骤

1、导入spring整合junit的坐标    spring-test坐标
  <dependency>            <groupId>org.springframeworkgroupId>             <artifactId>spring-testartifactId>            <version>5.0.2.RELEASEversion>   dependency>
2、使用junit提供的一个注解把原有的main方法替换了,替换成spring提供的
@RunWith
@RunWith(SpringJUnit4ClassRunner.class)
3、告知spring的运行器,spring的ioc创建是基于xml还是注解的,并且说明位置
@ContextConfiguration
Locations:指定xml文件的位置,加上classpath关键字,表示在类路径下classes:指定注解类所在的位置
当我们使用spring 5.x版本的时候,要求junit的jar必须是4.12及以上
<dependency>            <groupId>junitgroupId>            <artifactId>junitartifactId>            <version>4.12version> dependency>

测试类

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = SpringConfiguration.class)public class AccountServiceTest {   // private ApplicationContext ac;    @Autowired    private IAccountService as = null;    /*@Before    public void init(){        //1.获取容器        ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);        //2.得到业务层对象        as = ac.getBean("accountService",IAccountService.class);    }*/    @Test    public void testFindAll() {        //执行方法        List accounts = as.findAllAccount();        for(Account account : accounts){            System.out.println(account);        }    }

运行结果

228785889dd8aa68f5367ca5f9a03e74.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值