使用配置类而不使用XML文件(代替bean.xml)对spring进行配置

2023-02-12,,,,

以下类是一个配置类,它的作用和bean.xml是一样的
注解:
  @Configuration
    作用:
       用于指定当前类是一个spring配置类,当创建容器时会从该类上加载注解。
       获取容器时需要使用AnnotationApplicationContext(有@Configuration注解的类.class)。
       ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
    
属性: value:用于指定配置类的字节码
    细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。
  @ComponentScan
    作用: 用于通过注解指定Spring在创建容器时要扫描的包
     代替了:
    <!-- 告知spring在创建容器时要扫描的包 -->
    <context:component-scan base-package="com.itheima"></context:component-scan>

    属性: basePackages value  两者的作用是一样的,都是用于指定创建容器时要扫描的包
       我们使用此注解就等同于在xml中配置了
       需要扫描多个包时, 使用{}(即数组的赋值方式)
    源码:
  @Bean
    作用: 该注解只能写在方法上,表明使用此方法创建一个对象,并且放入spring容器
    属性: name 用于指定bean的id 默认值是当前方法的名称
    @Bean(name="runner")
    @Scope("prototype")
  public QueryRunner createQueryRunner(@Qualifier("ds2") DataSource dataSource){
  return new QueryRunner(dataSource);
  }

     代替了:

    <!--配置QueryRunner-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
    <!--注入数据源-->
    <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>
    @Bean(name="ds2")
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);
}
}

      代替了:

  <!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--连接数据库的必备信息-->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy"></property>
<property name="user" value="root"></property>
<property name="password" value="1234"></property>
</bean>

    细节: 当我们使用注解配置方法时, 如果方法有参数, spring框架回去容器中查找有没有类型同参数匹配 的bean对象

       查找的方式同AutoWired注解的方式是一样的

  @Import

    作用: 用于导入其他配置类,在引入其他配置类时,可以不用再写@Configuration注解。当然,写上也没问题。

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

         当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是子配置类

      @Configuration 
      @ComponentScan(basePackages = "com.itheima.spring")
      @Import({ JdbcConfig.class})
      public class SpringConfiguration { }
      @Configuration
      @PropertySource("classpath:jdbc.properties")
      public class JdbcConfig{ }

@PropertySource

  作用:用于加载.properties文件中的配置。
      例如我们配置数据源时,可以把连接数据库的信息写到properties配置文件中,
      就可以使用此注解指定properties配置文件的位置
   属性: value[]:用于指定properties文件位置。如果是在类路径下,需要写上classpath:
  

      

    在JdbcConfig中使用SpEL通过key获取properties文件中的相应的值     通过@Value注入

    

 
 

使用配置类而不使用XML文件(代替bean.xml)对spring进行配置的相关教程结束。