基于XML管理Bean

2.2.1、案例
  1. 创建 Maven Moudle

  2. 引入依赖

 
        
        
            org.springframework
            spring-context
            5.3.28
        
        
        
            junit
            junit
            4.12
            test
        
 

         3. 创建类Student

基于XML管理Bean_第1张图片

        4. 创建Spring的配置文件 applicationContext.xml

        5. 在Spring的配置文件中配置bean

基于XML管理Bean_第2张图片

 

 6. 创建测试类测试

注意:在Spring中获取bean,默认是通过反射调用无参构造方法,所以类中必须要提供一个无参构造方法

基于XML管理Bean_第3张图片

  1. 结果

2.2.2、获取Bean的三种方式
  1. 根据bean的id获取

  2. 根据bean的类型获取

    要求在配置文件中只能有一个该类匹配的bean,若有多个该类的Bean,会报错:NoUniqueBeanDefinitionException: No qualifying bean of type 'com.my.pojo.Student' available: expected single matching bean but found 2: studentOne,studentTwo

  3. 根据bean的id和类型获取

Spring的bean默认是单例的,若想多例,在bean标签中添加 scope="prototype"

  1. 如果组件类实现了接口,可以根据接口类型获取bean

    注意:bean得是唯一的

根据类型来获取bean时,在满足bean唯一性的前提下,只要:对象 instanceOf 类 的返回结果是true就可以认定为和类型匹配,能过获取到。

通过bean的的类型、bean所继承的类的类型,bean所实现的接口的类型都可以获取bean

2.2.3、依赖注入

为类中的属性赋值的过程就为依赖注入。

  1. setter注入


    
    
    
    
  1. 构造器注入


    
    
    
    
  1. 特殊值处理


    
    
    
        
    
    
  1. 为类属性赋值

  • 引用外部bean


    
    

    
    
    
    
    
  • 级联方式


    
    
    
    
        
        
            
            
        
    
  1. 为数组属性赋值


    
    
    
    
        
            
            吃饭
            睡觉
            打豆豆
        
    
  1. 为List集合类型赋值


    
    
    
        
            
            
            
        
    
  1. 为map集合赋值


    
    
    
    
        
        
    
  1. Spring管理数据源

①加入依赖


    mysql
    mysql-connector-java
    8.0.16



    com.alibaba
    druid
    1.0.31

②创建外部配置文件


         

    
    
    
    
    

③测试

@Test
public void testDataSource() throws SQLEXception {
    ApplicationContext ioc = new ClassPathXMLApplicationContext("applicationContext.xml");
    DruidDataSource dataSource = ioc.getBean(DruidDataSource.class);
    System.out.println(dataSource.getConnection);
}

④结果

你可能感兴趣的:(Spring,spring,java,xml)