@Autowired
使用@Autowired 标签注入ApplicationContext
package com.tntxia.bean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class User {
@Autowired
private ApplicationContext applicationContext;
public void show() {
System.out.println("User:"+applicationContext.getClass());
}
}
实现ApplicationContextAware接口
package com.tntxia.bean;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class Book implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext=applicationContext;
}
public void show() {
System.out.println("book:"+applicationContext.getClass());
}
}
Spring 4.3 新特性,直接在构造方法注入
package com.tntxia.bean;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class Bank {
private ApplicationContext applicationContext;
//spring 4.3 提供,与构造方法调用有关
public Bank(ApplicationContext applicationContext) {
this.applicationContext=applicationContext;
}
public void show() {
System.out.println("bank:"+applicationContext.getClass());
}
}
测试
package com.tntxia;
import com.tntxia.bean.Bank;
import com.tntxia.bean.Book;
import com.tntxia.bean.User;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.tntxia.bean");
User bean = (User) context.getBean("user");
bean.show();
Book bean2 = (Book) context.getBean("book");
bean2.show();
Bank bean3 = (Bank) context.getBean("bank");
bean3.show();
context.close();
}
}
运行结果:
说明,三个Bean都可以取到ApplicationContext