ApplicationContextAware 使用示例
ApplicationContextAware 使用示例
使用场景
有时候我们想用SpringBean容器动态管理一些容器,在运行时想动态拿到对应的SpringBean对象这时候我们就需要拿到ApplicationContext对象,使用该对象提供的方法获取SpringBean对象。
示例
首先继承ApplicationContextAware接口,这个SpringBean在启动的帮我set该对象,不懂原理的可以看SpringBean的生命周期,此处不多做介绍。
@Component
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 获取SpringBean容器对象
* @param name 容器名字
* @param clazz 容器对象类型
* @param <T>
* @return
*/
public static <T> T getBean(String name, Class<T> clazz){
// org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'demoPropertiesa' available
// 获取不到bean容器是,如果不想报错请做异常处理
return applicationContext.getBean(name, clazz);
}
}
测试的SpringBean对象 ,@Data 需要lombok的支持,如果没有正常写get和set即可。
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties("demo.config")
public class DemoProperties {
private String name;
}
配置文件 application.yml
demo:
config:
name: zkq
测试类
@SpringBootTest
class DemoApplicationTests {
@Test
void contextLoads() {
DemoProperties demoProperties = ApplicationContextUtil.getBean("demoProperties", DemoProperties.class);
System.out.println(demoProperties);
System.out.println(demoProperties.getName());
}
}
测试结果
// 如果不是lombok 这个出差会有差异,不影响使用
DemoProperties(name=zkq)
zkq
浙公网安备 33010602011771号