Spring @Import註解 —— 導入資源

 

在應用中,有時沒有把某個類注入到IOC容器中,但在運用的時候須要獲取該類對應的bean,此時就須要用到@Import註解。示例以下: 
先建立兩個類,不用註解注入到IOC容器中,在應用的時候在導入到當前容器中。 html

一、建立Dog和Cat類 

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

cat類spring

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

 

二、在啓動類中須要獲取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();
    }
}

三、運行該啓動類,輸出結果:spa

com.example.demo.Dog@4802796d
com.example.demo.Cat@34123d65

從輸出結果知,@Import註解把用到的bean導入到了當前容器中。3d

另外,也能夠導入一個配置類 
仍是上面的Dog和Cat類,如今在一個配置類中進行配置bean,而後在須要的時候,只須要導入這個配置就能夠了,最後輸出結果相同。code

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,以下使用:htm

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();
    }
}
相關文章
相關標籤/搜索