Java框架_Spring5_day05_IOC(注解)

目录

七、使用注解去掉 applicationContext.xml 中的所有配置

7.1 @Configuration

7.2 @ComponentScan 

7.3 @Bean

7.4 工厂AnnotationConfigApplicationContext.java

7.5 @Import

7.6 @PropertySource

7.7 @Qualifier

八、使用 Spring 整合 Junit

8.1 导入 Spring 整合 Junit 的坐标

8.2 测试类


七、使用注解去掉 applicationContext.xml 中的所有配置

7.1 @Configuration

@Configuration
public class SpringConfiguration {

}

       表示该类是一个配置类,它的作用和applicationContext.xml是一样的我们下面讲解的是spring5中的新注解

@Configuration

       作用:指定当前类是一个配置类,如同取代applicationContext.xml中的配置​

       细节:当配置类作为AnnotationConfigApplicationContext对象创建时,该注解可以不写

7.2 @ComponentScan 

@ComponentScan

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

       属性:​ value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包的范围。

@Configuration
@ComponentScan(value = {"com.cpz"})
public class SpringConfiguration {

}

上述代码相当于 xml 中配置的:

<context:component-scan base-package="com.cpz"></context:component-scan>

7.3 @Bean

@Bean

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

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

       细节:我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象,如果有bean对象,将对象通过方法的形参注入到方法中使用。查找的方式和Autowired注解的作用是一样的。

@Configuration
@ComponentScan(value = {"com.cpz"})
public class SpringConfiguration {

    /**
     * 用于创建一个QueryRunner对象
     * @param dataSource
     * @return
     */
    @Bean(name="queryRunner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name="dataSource")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            ds.setDriverClass("com.mysql.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/spring");
            ds.setUser("root");
            ds.setPassword("1234");
            return dataSource;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

7.4 工厂AnnotationConfigApplicationContext.java

       当配置类作为AnnotationConfigApplicationContext对象创建的参数时,@Configuration注解可以不写。

public class SpringTest {

    @Test
    public void testFindAll() {
        // 这里要使用 AnnotationConfigApplicationContext 实现类
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        AccountService accountService = ac.getBean("accountService",AccuntService.class);
        //3.执行方法
        List<Account> list= as.findAcountAll();
        for(Account account : list){
            System.out.println(account);
        }
    }
}

7.5 @Import

@Import​

       作用:用于导入其他的配置类​ 属性:

       value:用于指定其他配置类的字节码。

当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是子配置类,相当于applicationContext.xml中的<import resource=””>

首先我们将配置都放到 JdbcConfig.java 配置类中,然后在 SpringConfiguration.java 中引入 JdbcConfig.java 的配置

//@Configuration
@ComponentScan(value = {"com.cpz"})
@Import(value= JdbcConfig.class)
public class SpringConfiguration {

}

7.6 @PropertySource

@PropertySource​

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

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

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

//@Configuration
@ComponentScan(value = {"com.cpz"})
@Import(value= JdbcConfig.class)
@PropertySource("classpath:jdbc.properties")
public class SpringConfiguration {

}

关联好属性文件后,我们还要配置 JdbcConfig 配置类,使得创建数据源时使用的参数来自属性文件。

public class JdbcConfig {
    @Value("${jdbc.driverClass}")
    private String driver;
    @Value("${jdbc.jdbcUrl}")
    private String url;
    @Value("${jdbc.user}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean(name = "queryRunner")
    @Scope(value = "prototype")
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    @Bean(name = "ds")
    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);
        }
    }
}

7.7 @Qualifier

作用:如果spring容器中出现了多个数据源类型,使用该注解指定注入的数据源。

public class JdbcConfig {
    @Value("${jdbc.driverClass}")
    private String driver;
    @Value("${jdbc.jdbcUrl}")
    private String url;
    @Value("${jdbc.user}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

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

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

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

八、使用 Spring 整合 Junit

8.1 导入 Spring 整合 Junit 的坐标

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.0.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

8.2 测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class SpringTest {

    @Autowired
    AccountService accountService;

    @Test
    public void findAll(){
        List<Account> list = accountService.findAccountAll();
        for (Account account : list) {
            System.out.println(account);
        }
    }
}

总结:

@Runwith(加载 SpringJUnit4ClassRunner.class 

       使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的

@ContextConfiguration

       告知spring的运行器,spring和ioc创建是基于xml还是基于注解的,并且说明位置

        locations:指定xml文件的位置,加上classpath关键字,表示在类路径下

                @ContextConfiguration(locations = "classpath:applicationContext.xml")
        classes:指定注解类所在地位置

                @ContextConfiguration(classes = SpringConfiguration.class)   

注意:当我们使用spring 5.x版本的时候,要求junit的jar必须是4.12及以上

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值