天天看點

Spring @Import注解

在應用中,有時沒有把某個類注入到IOC容器中,但在運用的時候需要擷取該類對應的bean,此時就需要用到@Import注解。示例如下: 

先建立兩個類,不用注解注入到IOC容器中,在應用的時候在導入到目前容器中。 

1、建立Dog和Cat類 

Dog類:

package com.example.demo;
 
public class Dog {
 
}


package com.example.demo;
 
public class Cat {
 
}
           

2、在啟動類中需要擷取Dog和Cat對應的bean,需要用注解@Import注解把Dog和Cat的bean注入到目前容器中。

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
 
//@SpringBootApplication
@ComponentScan
/*把用到的資源導入到目前容器中*/
@Import({Dog.class, Cat.class})
public class App {
 
    public static void main(String[] args) throws Exception {
 
        ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
        System.out.println(context.getBean(Dog.class));
        System.out.println(context.getBean(Cat.class));
        context.close();
    }
}
           

3、運作該啟動類,輸出結果:

[email protected]
[email protected]
           

從輸出結果知,@Import注解把用到的bean導入到了目前容器中。

另外,也可以導入一個配置類 

還是上面的Dog和Cat類,現在在一個配置類中進行配置bean,然後在需要的時候,隻需要導入這個配置就可以了,最後輸出結果相同。

MyConfig 配置類:

package com.example.demo;
import org.springframework.context.annotation.Bean;
 
public class MyConfig {
 
    @Bean
    public Dog getDog(){
        return new Dog();
    }
 
    @Bean
    public Cat getCat(){
        return new Cat();
    }
 
}
           

比如若在啟動類中要擷取Dog和Cat的bean,如下使用

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
 
//@SpringBootApplication
@ComponentScan
/*導入配置類就可以了*/
@Import(MyConfig.class)
public class App {
 
    public static void main(String[] args) throws Exception {
 
        ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
        System.out.println(context.getBean(Dog.class));
        System.out.println(context.getBean(Cat.class));
        context.close();
    }
}