问题
As most of Spring Boot new users I have a problem with @Autowired :D
I've readed a big amount of topics about this annotation here But still can't find proper solution for my problem.
Let's suppose that we have this Spring Boot hierarchy:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Class, that we wanna instantiate every time it's called:
@Service
public class TestWire {
public TestWire() {
System.out.println("INSTANCE CREATED: " + this);
}
}
Out get controller, that creates new SomeRepo object every request:
@RestController
public class CreatingRepo {
@RequestMapping("/")
public void postMessage() {
SomeRepo repo = new SomeRepo();
}
}
Finally, class, that uses @Autowired to create TestWire instances:
public class SomeRepo {
@Autowired
private TestWire testWire;
public SomeRepo() {
System.out.println(testWire.toString());
}
}
Let's assume, that we make GET request to "/" several times.
So, as a result, TestWire class will isntantiate only when project builds and neither @Scope(value = "prototype"), nor proxyMode = ScopedProxyMode.TARGET_CLASS wont help.
Any ideas how to create new instances at runtime? I mean, how can we do it in "Spring way"? Without factories and other things, only Spring DI through annotation and configuration.
Upd. A piece of stack trace, where instance created:
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()
回答1:
If I understood you correct you need to annotate the SomeRepo
like this:
@Service
@Scope(value = "prototype")
public class SomeRepo {
// ...
}
Option A:
Instead of instantiating the class with new SomeRepo();
you ask the BeanFactory.getBean(...)
for it.
@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);
}
}
Option B:
You should also be able to get the Bean like this (over paramters without the 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.
}
}
来源:https://stackoverflow.com/questions/33740510/spring-boot-autowired-creating-instances-on-a-runtime