注解方式的spring

122 阅读2分钟

spring的新注解

Configuration

  • 作用:指定当前类是一个配置类,它的作用和bean.xml是一样的
  • 细节:当配置类作为AnnotationConfigApplicationContext对象的参数时,该注解可以不写
@Configuration
public class SpringConfiguration{}

ComponentScan

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

  • 属性:

    • value:它和basePackage的作用是一样的,都是指定要扫描的包

      ​ 我们使用注解就相当于在xml中配置了

      <context:component-scan base-package="com.itcast"></context:component-scan>
      
@Configuration
@ComponentScan(value={"com.itcast"})
public class SpringConfiguration{}

Bean

  • 作用:用于把当前方法的返回值作为bean对象存入容器
  • 属性:
    • name:用于指定bean对象的id。当不写时,默认是当前方法的名称
//创建QuerryRunner对象
@Bean(name="runner")
public QueryRunner createQueryRunner(DataSource dataSource){
    return new QueryRunner(dataSource);
}

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

    ​ 当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象

    ​ 查找的方式和Autowired注解的作用是一样的

  • ==注意==:Bean注解创建的对象默认是单例的,需要改成多例,则要加上Scope注解


Import

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

  • 属性:

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

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


PropertySource

  • 作用:用于指定properties文件的位置,内容通过SpEL获取

  • 属性:

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

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

//主配置类
@Configuration
@ComponentScan("com.itcast")
@Import(xxxConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration{
    
}

//jdbc配置类
@Configuration
public class JdbcConfig{
    @Value("${jdbc.driver}")//properties中的key
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    .....
}

纯注解配置的使用

  • AnnotationConfigApplicationContext对象

    ​ 注意:当使用纯注解时,获取容器使用此对象(而不是ClassPathXmlApplicationContext),参数是配置类的class