spring-03 IOC注解相关

た 入场券 2022-03-16 02:56 345阅读 0赞

文章目录

  • 1.基于注解的IOC配置
    • 1.1 applicationContext.xml
    • 1.2 类添加注解
      • 1.2.1 @Component
      • 1.2.2 Spring中提供了@Component的衍生注解
    • 1.3 测试方法
    • 2.注解配置-依赖注入
    • 2.1 @Autowired
    • 2.2 @Qualifier
    • 2.3 @Resource
    • 2.4 @Value
  • 2.4.1 @Value(“#{}“)与@Value(“${}“)的区别
  • 3.注解配置-作用域
    • 3.1 @Scope
  • 4.注解配置-初始化和销毁(单例)
  • 5.配置文件引用
  • 6.使用spring的注解配置,去掉applicationContext.xml中所有配置(springboot基础)
    • 6.1 配置类
      • 6.1.1 @Configuration注解
      • 6.1.2 @ComponentScan
      • 6.1.3 @Bean
    • 6.2 测试
    • 6.3 @Import注解
    • 6.4 @PropertySource
    • 6.5 @Qualifier
  • 7.使用spring整合Junit
    • 7.1 添加maven依赖
    • 7.2 使用

1.基于注解的IOC配置

1.1 applicationContext.xml

  1. <!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是一个名称为context名称空间和约束中-->
  2. <!--<context:annotation-config> 和 <context:component-scan>的区别-->
  3. <!--<context:annotation-config> 是用于激活那些已经在spring容器里注册过的bean(无论是通过xml的方式还是通过package sanning的方式)上面的注解。-->
  4. <!--<context:component-scan>除了具有<context:annotation-config>的功能之外,<context:component-scan>还可以在指定的package下扫描以及注册javabean 。-->
  5. <!--<context:annotation-config/>-->
  6. <context:component-scan base-package="com.myx"></context:component-scan>

1.2 类添加注解

在这里插入图片描述

1.2.1 @Component

用于把当前类对象存入spring容器中
属性:value:用于指定bean的id。当我们不写时,它的默认值是当前类名,且首字母改小写。

1.2.2 Spring中提供了@Component的衍生注解

  • @Controller:用来修饰WEB层类(控制层)(springMVC延用了该注解)
  • @Service:用来修饰service层类(业务层)
  • @Repository:用来修饰DAO层类(持久层)

以上三个注解他们的作用和属性与Component是一模一样。
他们三个是spring框架为我们提供明确的三层使用的注解,使我们的三层对象更加清晰。

1.3 测试方法

  1. import org.springframework.context.support.ClassPathXmlApplicationContext;
  2. /** * 描述:测试注解bean * @author: myx * @date: 2019/1/10 * 注意:本内容仅限于学习使用 * Copyright © 2019-myx. All rights reserved. */
  3. public class Test {
  4. public static void main(String[] args) {
  5. /** * 【ApplicationContext 接口的实现类 】 (1)ClassPathXmlApplicationContext: 它是从类的根路径下加载配置文件 推荐使用这种 (2)FileSystemXmlApplicationContext: 它是从磁盘路径上加载配置文件,配置文件可以在磁盘的任意位置。注意磁盘的权限 (3)AnnotationConfigApplicationContext: 当我们使用注解配置容器对象时,需要使用此类来创建spring 容器。它用来读取注解。 */
  6. ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
  7. HelloSpringAnn bean = ac.getBean(HelloSpringAnn.class);
  8. System.out.println(bean);
  9. }
  10. }

2.注解配置-依赖注入

2.1 @Autowired

自动按照类型注入。只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功,如果ioc容器中没有任何bean的类型和要注入的变量类型匹配,则报错,如果Ioc容器中有多个类型匹配时:
先按照类型匹配,如果不能匹配上,会按照属性的名称进行匹配

  • 出现位置:可以是变量上,也可以是set方法上
  • 细节:在使用注解注入时,set方法就不是必须的了。
  • 注入集合

    1. 第一步:
    2. @Bean
    3. Public List<User> createList(){
    4. // 组织数据
    5. List<User> list = new ArrayList<User>();
    6. return list;
    7. }
    8. 第二步:
    9. @Autowired
    10. private List<User> list;

2.2 @Qualifier

在按照类中注入的基础之上再按照名称注入。
属性:value:用于指定注入bean的id。

在这里插入图片描述

2.3 @Resource

直接按照bean的id注入。如果id属性不存在,可以再按照类型注入。它可以独立使用
属性:name:用于指定bean的id,如果指定name,只能按照bean的id注入,不能按照类型注入。

以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现(使用@Value)

2.4 @Value

用于注入基本类型和String类型的数据
属性:value:用于指定数据的值。使用${表达式}可以读取配置文件(.properties文件)的信息

  1. @Value(value = "myx")
  2. private String name;
  3. @Value(value = "18")
  4. private Integer age;

2.4.1 @Value(“#{}“)与@Value(“${}“)的区别

区别

3.注解配置-作用域

3.1 @Scope

用于指定bean的作用范围
属性:value:指定范围的取值。常用取值:singleton prototype

在这里插入图片描述

4.注解配置-初始化和销毁(单例)

  1. @PostConstruct
  2. public void init(){
  3. System.out.println("初始化方法执行了");
  4. }
  5. @PreDestroy
  6. public void destroy(){
  7. System.out.println("销毁方法执行了");
  8. }

5.配置文件引用

使用import加载多个applicationContext.xml

让程序加载多个spring的配置文件,对spring的配置文件细分

  • applicationContext.xml:加载第三方的配置(数据源、QueryRunner)
  • applicationContext-dao.xml:加载自己创建的Dao对象
  • applicationContext-service.xml:加载自己创建的Service对象


6.使用spring的注解配置,去掉applicationContext.xml中所有配置(springboot基础)

6.1 配置类

表示该类是一个配置类,它的作用和applicationContext.xml是一样的

  1. @Configuration
  2. @ComponentScan(value = {"com.myx"})
  3. public class SpringConfiguration {
  4. }

6.1.1 @Configuration注解

作用:指定当前类是一个配置类,如同applicationContext.xml中的配置
细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。

6.1.2 @ComponentScan

用于通过注解指定spring在创建容器时要扫描的包
属性:value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包的范围。
我们使用此注解就等同于在xml中配置了:

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

6.1.3 @Bean

用于把当前方法的返回值作为bean对象存入spring的ioc容器中.
属性:name:用于指定bean的id。当不写时,默认值是当前方法的名称
依赖注入细节:
我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象,如果有bean对象,将对象通过方法的形参注入到方法中使用。查找的方式和Autowired注解的作用是一样的

  1. /**
  2. * 创建数据源对象
  3. * @return
  4. */
  5. @Bean(name="ds")
  6. public DataSource createDataSource(){
  7. try {
  8. ComboPooledDataSource ds = new ComboPooledDataSource();
  9. ds.setDriverClass("com.mysql.jdbc.Driver");
  10. ds.setJdbcUrl("jdbc:mysql://localhost:3306/itcastspring");
  11. ds.setUser("root");
  12. ds.setPassword("root");
  13. return ds;
  14. }catch (Exception e){
  15. throw new RuntimeException(e);
  16. }
  17. }

6.2 测试

  1. public class AccountServiceTest {
  2. @Test
  3. public void testFindAll() {
  4. ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
  5. HelloSpringAnn bean = ac.getBean(HelloSpringAnn.class);
  6. System.out.println(bean);
  7. }
  8. }

6.3 @Import注解

用于导入其他的配置类

属性:value:用于指定其他配置类的字节码。
当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是子配置类
相当于:

  1. applicationContext.xml中的<import resource=””>
  2. public class JdbcConfig {
  3. /**
  4. * 用于创建一个QueryRunner对象
  5. * @param dataSource
  6. * @return
  7. */
  8. @Bean(name="runner")
  9. @Scope("prototype")
  10. public QueryRunner createQueryRunner(DataSource dataSource){
  11. return new QueryRunner(dataSource);
  12. }
  13. /**
  14. * 创建数据源对象
  15. * @return
  16. */
  17. @Bean(name="ds")
  18. public DataSource createDataSource(){
  19. try {
  20. ComboPooledDataSource ds = new ComboPooledDataSource();
  21. ds.setDriverClass("com.mysql.jdbc.Driver");
  22. ds.setJdbcUrl("jdbc:mysql://localhost:3306/itcastspring");
  23. ds.setUser("root");
  24. ds.setPassword("root");
  25. return ds;
  26. }catch (Exception e){
  27. throw new RuntimeException(e);
  28. }
  29. }
  30. }
  31. @ComponentScan(value = {"com.nyx"})
  32. @Import(value= JdbcConfig.class)
  33. public class SpringConfiguration {
  34. }

6.4 @PropertySource

用于指定properties文件的位置
属性:value:指定文件的名称和路径。关键字:classpath,表示类路径下

  1. @ComponentScan(value = {"com.myx"})
  2. @Import(value= JdbcConfig.class)
  3. @PropertySource("classpath:jdbcConfig.properties")
  4. public class SpringConfiguration {
  5. }

6.5 @Qualifier

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

  1. @Bean(name="runner")
  2. @Scope("prototype")
  3. public QueryRunner createQueryRunner(@Qualifier(value = "ds2") DataSource dataSource){
  4. return new QueryRunner(dataSource);
  5. }

7.使用spring整合Junit

7.1 添加maven依赖

  1. <dependency>
  2. <groupId>org.springframework</groupId>
  3. <artifactId>spring-test</artifactId>
  4. <version>5.0.2.RELEASE</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>junit</groupId>
  8. <artifactId>junit</artifactId>
  9. <version>4.12</version>
  10. </dependency>

7.2 使用

  1. /**
  2. * 使用Junit单元测试:测试我们的配置
  3. * Spring整合junit的配置
  4. * 1、导入spring整合junit的jar(坐标)
  5. * 2、使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的
  6. * @Runwith
  7. * 3、告知spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置
  8. * @ContextConfiguration
  9. * locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
  10. * classes:指定注解类所在地位置
  11. *
  12. * 当我们使用spring 5.x版本的时候,要求junit的jar必须是4.12及以上
  13. */
  14. @RunWith(SpringJUnit4ClassRunner.class)
  15. @ContextConfiguration(classes = SpringConfiguration.class)
  16. public class AccountServiceTest {
  17. @Autowired
  18. private AccountService as;
  19. @Test
  20. public void testFindAll() {
  21. //3.执行方法
  22. List<Account> accounts = as.findAllAccount();
  23. for(Account account : accounts){
  24. System.out.println(account);
  25. }
  26. }
  27. }

发表评论

表情:
评论列表 (有 0 条评论,345人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Spring篇】IOC相关内容

    通过前面两个案例,我们已经学习了bean如何定义配置DI如何定义配置以及容器对象如何获取的内容,接下来主要是把这三块内容展开进行详细的讲解,深入的学习下这三部分的内容,首...

    相关 Spring5学习03:IOC注解

    1.注解 > 1. 注解是代码特殊标记,格式:@注解名称(属性名称=属性值, 属性名称=属性值…) > 2. 使用注解,注解作用在类上面,方法上面,属性上面 > 3.