作为大多数 Spring Boot 新用户,我对 @Autowired 有问题:D
我在这里阅读了大量有关此注释的主题,但仍然无法为我的问题找到合适的解决方案。
假设我们有这个 Spring Boot 层次结构:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
类,我们想在每次调用时实例化:
@Service
public class TestWire {
public TestWire() {
System.out.println("INSTANCE CREATED: " + this);
}
}
取出 Controller ,它会在每个请求中创建新的 SomeRepo 对象:
@RestController
public class CreatingRepo {
@RequestMapping("/")
public void postMessage() {
SomeRepo repo = new SomeRepo();
}
}
最后,使用@Autowired 创建 TestWire 实例的类:
public class SomeRepo {
@Autowired
private TestWire testWire;
public SomeRepo() {
System.out.println(testWire.toString());
}
}
假设我们多次向“/”发出 GET 请求。
因此,因此,TestWire 类仅在项目构建时才会生效,而 都不会。 @Scope(value = "prototype") ,也不是 proxyMode = ScopedProxyMode.TARGET_CLASS 不会有帮助。
任何想法如何在运行时创建新实例?我的意思是,我们如何以“Spring 方式”做到这一点?没有工厂等东西,只有通过注解和配置的Spring DI。
更新。一段堆栈跟踪,其中创建了实例:
2015-11-16 20:30:41.032 INFO 17696 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
INSTANCE CREATED: com.example.TestWire@56c698e3
2015-11-16 20:30:41.491 INFO 17696 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@12f41634: startup date [Mon Nov 16 20:30:37 MSK 2015]; root of context hierarchy
2015-11-16 20:30:41.566 INFO 17696 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public void com.example.CreatingRepo.postMessage()
最佳答案
如果我理解你是正确的,你需要注释 SomeRepo
像这样:
@Service
@Scope(value = "prototype")
public class SomeRepo {
// ...
}
选项 A:
而不是使用
new SomeRepo();
实例化类你问BeanFactory.getBean(...)
为了它。@RestController
public class CreatingRepo {
@Autowired
BeanFactory beanFactory;
@RequestMapping("/")
public void postMessage() {
// instead of new SomeBean we get it from the BeanFactory
SomeRepo repo = beanFactory.getBean(SomeRepo.class);
}
}
选项 B:
您还应该能够像这样获得 Bean(在没有
beanFactory
的参数上):@RestController
public class CreatingRepo {
@RequestMapping("/")
public void postMessage(SomeRepo repo) {
// instead of the BeanFactory and using new SomeRepo you can get it like this.
}
}
关于java - Spring Boot @Autowired 在运行时创建实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33740510/