package yzztcl.hs.util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import java.util.Map;
/**
* @author yzz
* @date 2022/1/6 11:04
*/
@Slf4j
@Configuration
public class ApplicationContextUtil implements ApplicationContextAware {
public static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationParam) throws BeansException {
ApplicationContextUtil.applicationContext=applicationParam;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 通过类获得bean
* @param clazz classzz.class
* @param <T>
* @return
*/
public static <T> T getBean(Class<T> clazz) {
try {
return applicationContext.getBean(clazz);
} catch (BeansException var2) {
log.warn("Bean is not exist {}", clazz.getName());
return null;
}
}
/**
* 通过@Component("test") 获得 ===>
* @param beanName test
* @return
*/
public static Object getBean(String beanName) {
try {
return applicationContext.getBean(beanName);
} catch (BeansException var2) {
log.warn("Bean is not exist {}", beanName);
return null;
}
}
public static <T> String[] getBeanNames(Class<T> clazz) {
try {
return applicationContext.getBeanNamesForType(clazz);
} catch (BeansException var2) {
log.warn("Bean is not exist for class:{}", clazz);
return null;
}
}
public static <T> Map<String, T> getBeansForType(Class<T> clazz) {
try {
return applicationContext.getBeansOfType(clazz);
} catch (BeansException var2) {
log.warn("Bean is not exist for class:{}", clazz);
return null;
}
}
public static <T> T getBean(String beanName, Class<T> clazz) {
try {
return applicationContext.getBean(beanName, clazz);
} catch (BeansException var3) {
log.warn("Bean is not exist {} of {}", beanName, clazz.getName());
return null;
}
}
}
调用示例:
LoginService
@Service
public class LoginService {
public void test(){
System.out.println("you can you up ,no can no bb!");
}
}
@Component("loginService ")
public class LoginService {
public void test(){
System.out.println("you can you up ,no can no bb!");
}
}
LoginService loginService1 = ApplicationContextUtil.getBean(LoginService.class);
LoginService loginService2 = ApplicationContextUtil.getBean("loginService ");
loginService1 .test();
loginService2 .test();