SpringBoot @Import和@ImportResource详解

概述:
@Import注解是引入java类:

  1. 导入@Configuration注解的配置类(4.2版本之前只可以导入配置类,4.2版本之后也可以导入普通类)
  2. 导入ImportSelector的实现类
  3. 导入ImportBeanDefinitionRegistrar的实现类

@ImportResource是引入spring配置文件.xml

config包下的三个配置类
 

CDConfig.java:
package com.jiaobuchong.config;
 
import com.jiaobuchong.dao.CompactDisc;
import com.jiaobuchong.soundsystem.SgtPeppers;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration  // @Configuration注解表示定义一个配置类
public class CDConfig {
            // 方法名heyGirl即是bean的name
    @Bean   // 将SgtPeppers注册为 SpringContext中的bean
    public CompactDisc heyGirl() {
        return new SgtPeppers();  // CompactDisc类型的
    }
}

@Bean注解等同于xml的配置:





CDPlayerConfig.java:

package com.jiaobuchong.config;
 
import com.jiaobuchong.dao.CompactDisc;
import com.jiaobuchong.soundsystem.CDPlayer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
 
@Configuration
@Import(CDConfig.class)  //导入CDConfig的配置
public class CDPlayerConfig {
    @Bean(name = "cDPlayer")
    public CDPlayer cdPlayer(CompactDisc heyGirl) {  
    /* 这里注入的bean是
    上面CDConfig.java中的name为heyGirl的CompactDisc类型的bean*/
        return new CDPlayer(heyGirl);
    }
 
}

这里的注解@Bean等同于xml配置的元素,






 

SoundSystemConfig.java:

package com.jiaobuchong.config;
 
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
 
@Configuration
@Import(CDPlayerConfig.class)  
@ImportResource("classpath:cons-injec.xml") //导入xml配置项
public class SoundSystemConfig {
 
}

@ImportResource等同于xml配置:

xml配置文件
cons-injec.xml:



       
              
                     
                            Sgt. Pepper's Lonely Hearts Club Band
                            With a Little Help from My Friends
                            Lucy in the Sky with Diamonds
                            Getting Better
                            Fixing a Hole
                            
                     
              
       


 

你可能感兴趣的:(SpringBoot,注解)