我有一个这样的服务类:
@Service
public class CompanyServiceImpl implements CompanyService {
@Autowired
private CompanyDAO companyDAO;
@Transactional
public void addOrUpdateCompany(Company company) {
companyDAO.addOrUpdateCompany(company);
}
}
通常,我可以通过以下方式从Spring获得CompanyService的实例:
@Autowired
CompanyService companyService;
但是,在某些情况下,我想在没有@Autowired的情况下创建/获取CompanyService的安装:
CompanyService companyService = XXX.getxxx("CompanyService");
有什么办法可以做到这一点?
最佳答案
其他方式是
@Component
public class ContextHolder implements ApplicationContextAware {
private static ApplicationContext CONTEXT;
public void setApplicationContext(ApplicationContext applicationContext) {
CONTEXT = applicationContext;
}
public static ApplicationContext getContext() {
return CONTEXT;
}
}
And then
CompanyService service = ContextHolder.getContext().getBean(CompanyService.class);