Spring容器の例を取得します.
1.紹介
Spring環境でクラスの例を取得したいのですが、直接newが出てきたら、Spring容器の中の新しいオブジェクトを作成しただけです.したがって、クラスで@Value、@Autowiredなどの注釈を使用しても機能しないので、Spring容器に注入されたインスタンスを取得する必要があります.
2.実現
Spring環境でクラスの例を取得したいのですが、直接newが出てきたら、Spring容器の中の新しいオブジェクトを作成しただけです.したがって、クラスで@Value、@Autowiredなどの注釈を使用しても機能しないので、Spring容器に注入されたインスタンスを取得する必要があります.
2.実現
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @describe: springcontext bean
*/
@Component
public class SpringContextUtil implements ApplicationContextAware {
public static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
SpringContextUtil.context = context;
}
/**
*
* @param beanId Spring bean ID
* @param clazz bean class
*/
public static T getBean(String beanId, Class clazz){
return context.getBean(beanId, clazz);
}
public static ApplicationContext getContext(){
return context;
}
}