获取spring窗口中的注入的类
获取spring窗口中的注入的类
package com.yy.utils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @author yayun
* @version 1.0
* @description TODO
* @date 2023/5/7 9:13
*/
@Component
public class ApplicationContextHolder implements ApplicationContextAware , InitializingBean {
private static ApplicationContext holdApplicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
holdApplicationContext = applicationContext;
}
public static <T> T getBeanByName(String beanName, Class<T> clazz){
T contextBean = holdApplicationContext.getBean(beanName, clazz);
return contextBean;
}
@Override
public void afterPropertiesSet() throws Exception {
String[] names = holdApplicationContext.getBeanDefinitionNames();
for (String name : names) {
System.out.println(">>>>>>" + name);
}
System.out.println("------\nBean 总计:" + holdApplicationContext.getBeanDefinitionCount());
}
}
可与场景使用结合
public interface Eat {
void test(Person person);
}
@Component("easy")
public class Eat1Impl implements Eat {
@Override
public void test(Person person) {
System.out.println("简单的吃" + person);
}
}
@Component("complex")
public class Eat2Impl implements Eat {
@Override
public void test(Person person) {
System.out.println("复杂的吃" + person);
}
}
@Data
public class Person {
private String name;
private Integer age;
}
@RestController
public class TestController {
@GetMapping("/test1/{name}")
public Object tess1(@PathVariable String name){
Person person = new Person();
person.setAge(20);
person.setName("张三");
ApplicationContextHolder.getBeanByName(name, Eat.class).test(person);
return "123";
}
@GetMapping("/test2/{name}")
public Object tess2(@PathVariable String name){
Person person = new Person();
person.setAge(48);
person.setName("李四");
ApplicationContextHolder.getBeanByName(name, Eat.class).test(person);
return "1234";
}
}