spring注入ApplicationContext对象的几种方式

实现接口方式:

@Component
public class Shop implements ApplicationContextAware{

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }

    public  void print(){
        System.out.println("*******"+applicationContext.getClass().getName());
    }
}

在@Component、@Configuration、@Service等注解下直接通过Autowired注入:

@Component
public class TestDirect{
 
    @Autowired
    private ApplicationContext applicationContext;
 
    public void print(){
        System.out.println("*********"+applicationContext.getClass().getName());
    }
}

构造器注入:

@Component
public class TestConstructor {
    private ApplicationContext applicationContext;
 
    public TestConstructor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
 
    public  void print(){
        System.out.println("********"+applicationContext.getClass().getName());
    }
}

@Configuration注解所注释的配置类也可通过构造函数注入ApplicationContext

代码:

public interface AA {
    int f();
}
public class BB implements AA {
    @Override
    public int f() {
        return 6;
    }
}
@Configuration
public class TestBean {

    @Bean
    public Computer computer16(){
        return new Computer("HP");
    }

    @ConditionalOnBean(Cpu.class)
    @Bean
    public BB computer2(Cpu computer){
        System.out.println("----********"+computer);
        return new BB();
    }

}

可以通过构造函数注入ApplicationContext

@Configuration
public class ConfigTestConstr {
    private ApplicationContext applicationContext;

    public ConfigTestConstr(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @PostConstruct
    public void initConsumer() {
        System.out.println(applicationContext.getBean(BB.class).f());
    }
}

启动类:

public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SourcecodeApplication.class);
//        AA aa = context.getBean(BB.class);
//        System.out.println(aa.f());
    }

}
原创文章 317 获赞 416 访问量 112万+

猜你喜欢

转载自blog.csdn.net/u014082714/article/details/105042227