在應用中,有時沒有把某個類注入到IOC容器中,但在運用的時候需要獲取該類對應的bean,此時就需要用到@Import注解。示例如下:
先創建兩個類,不用注解注入到IOC容器中,在應用的時候在導入到當前容器中。
1、創建Dog和Cat類
package com.example.demo; public class Dog { }
cat類
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、運行該啟動類,輸出結果:
com.example.demo.Dog@4802796d
com.example.demo.Cat@34123d65
從輸出結果知,@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(); } }