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();
    }
}
相关文章
相关标签/搜索