一、spring上下文
1.1 什么是spring上下文
1.2 spring上下文的作用
二、如何使用spring上下文
有四种方式获得spring上下文
- 方式一:实现ApplicationContextAware接口
- 方式二:非static方法版
- 方式三:在springboot引导类中设置
- 方式四;直接注入ApplicationContext
2.1 实现ApplicationContextAware接口
提供static方法供调用者使用,不要求使用者受spring容器管理
package net.facelib.eam.plancenter.webController.service.impl;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @author lc
* @version 1.0
* @date 2022/7/26 9:28
*/
@Component
public class MyTestService implements ApplicationContextAware {
public static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
MyTestService.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return MyTestService.applicationContext;
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
public static <T>T getBean(Class clazz) {
return (T)getApplicationContext().getBean(clazz);
}
public static <T>T getBean(String name, Class clazz) {
return (T)getApplicationContext().getBean(name,clazz);
}
}
2.2 同方法一,但是是非static方法版
使用者也得是被spring管理的bean,注入使用
2.3 在springboot引导类(启动类)里设置,此时就不需要实现ApplicationContextAware接口
@SpringBootApplication
public class MainApplication{
public static void main(String[] args) {
ConfigutableApplicationContext context = SpringApplication.run(MainApplication.clss,args)
MyTestService.setApplicationContext(context);
}
}
package net.facelib.eam.plancenter.webController.service.impl;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @author lc
* @version 1.0
* @date 2022/7/26 9:28
*/
@Component
public class MyTestService{
public static ApplicationContext applicationContext;
public static void setApplicationContext(ApplicationContext applicationContext) {
MyTestService.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return MyTestService.applicationContext;
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
public static <T>T getBean(Class clazz) {
return (T)getApplicationContext().getBean(clazz);
}
public static <T>T getBean(String name, Class clazz) {
return (T)getApplicationContext().getBean(name,clazz);
}
}
2.4 直接注入ApplicationContext
@Component
public class ContextUser{
// 在需要使用上下文的地方直接注入,前提,被spring管理
@Autowired
public ApplicationContext applicationContext;
}
|