我有这样的界面
@Repository
public interface CarRepository extends JpaRepository<Car, Long> {
}
在带有@RestController注释的类中,Spring能够与适当的字段连接。
但是,如果我想在春季创建没有任何注释的类,该怎么办?我必须创建此存储库的实现吗?如果是,我可以像春天一样吗?
答案 0 :(得分:0)
注入
private final ConfigurableApplicationContext configurableApplicationContext;
实例化您所需的班级。然后致电:
YourClass yourClass = (YourClass) configurableApplicationContext.getBeanFactory().initializeBean(new YourClass(), "YourClassName");
然后,您的类将保存一个已初始化的YourClass实例,就好像它是Spring @Component
(或@RestController
,从依赖项注入的角度来看是相同的)一样。< / p>
答案 1 :(得分:-1)
@SpringBootApplication
public class MainApplication extends SpringBootServletInitializer implements ApplicationContextAware {
private static ApplicationContext appContext;
public static void main(String[] args) {
SpringApplication.run(CrawlerApplication.class, args);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.appContext = applicationContext;
}
....
MainApplication.getAppContext().getBean(CarRepository.class)