Spring Boot @Autowired在运行时创建实例

Sup*_*upo 2 java spring dependency-injection autowired spring-boot

作为大多数Spring Boot新用户,我遇到了@Autowired:D的问题

我在这里引用了关于这个注释的大量话题,但仍然无法找到适合我的问题的解决方案.

我们假设我们有这个Spring Boot层次结构:

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

类,我们想要每次调用时实例化:

@Service
public class TestWire {
    public TestWire() {
        System.out.println("INSTANCE CREATED: " + this);
    }
}
Run Code Online (Sandbox Code Playgroud)

out get controller,每次请求都会创建新的SomeRepo对象:

@RestController
public class CreatingRepo {
    @RequestMapping("/")
    public void postMessage() {
        SomeRepo repo = new SomeRepo();
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,使用@Autowired创建TestWire实例的类:

public class SomeRepo {
    @Autowired
    private TestWire testWire;

    public SomeRepo() {
        System.out.println(testWire.toString());
    }
}
Run Code Online (Sandbox Code Playgroud)

我们假设,我们多次向"/"发出GET请求.

因此,因此,只有在项目构建时,TestWire类才会同步,并且@Scope(value ="prototype")proxyMode = ScopedProxyMode.TARGET_CLASS都不会有帮助.

有关如何在运行时创建新实例的任何想法?我的意思是,我们怎样才能以"春天的方式"做到这一点?没有工厂和其他东西,只有Spring DI通过注释和配置.

UPD.一个堆栈跟踪,其中创建了实例:

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()
Run Code Online (Sandbox Code Playgroud)

d0x*_*d0x 7

如果我理解你是正确的,你需要注释SomeRepo这样:

@Service
@Scope(value = "prototype")
public class SomeRepo { 
// ...
}
Run Code Online (Sandbox Code Playgroud)

选项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);
    }
}
Run Code Online (Sandbox Code Playgroud)

选项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.
    }
}
Run Code Online (Sandbox Code Playgroud)