站在巨人的肩膀上搬砖

导航

 

定义

@Component
public class ApplicationContextHelper implements ApplicationContextAware {

    private static ApplicationContext _context;

    @Autowired
    @Primary
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        _context = applicationContext;
    }

    public static ApplicationContext applicationContext() {
        return _context;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T)_context.getBean(name);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return _context.getBean(name, requiredType);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> requiredType) throws BeansException {
        return _context.getBean(requiredType);
    }

}

定义bean

@Service
public class TestService {}

使用

TestService ts = ApplicationContextHelper.getBean(TestService.class);
posted on 2021-11-04 14:17  站在巨人的肩膀上搬砖  阅读(168)  评论(0)    收藏  举报