我想在Spring Java配置中创建一个Spring bean,并在运行时传递一些构造函数参数.我创建了以下Java配置,其中有一个bean fixedLengthReport,它需要构造函数中的一些参数.
@Configuration
public class AppConfig {
@Autowrire
Dao dao;
@Bean
@Scope(value = "prototype")
**//SourceSystem can change at runtime**
public FixedLengthReport fixedLengthReport(String sourceSystem) {
return new TdctFixedLengthReport(sourceSystem, dao);
}
}
Run Code Online (Sandbox Code Playgroud)
但我收到的错误是sourceSystem无法连接,因为没有找到bean.如何使用运行时构造函数参数创建bean?
我使用的是Spring 4.2
我有一个原型范围bean,我希望通过@Autowired注释注入它.在这个bean中,还有@PostConstruct方法,Spring没有调用它,我不明白为什么.
我的bean定义:
package somepackage;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
@Scope("prototype")
public class SomeBean {
public SomeBean(String arg) {
System.out.println("Constructor called, arg: " + arg);
}
@PostConstruct
private void init() {
System.out.println("Post construct called");
}
}
Run Code Online (Sandbox Code Playgroud)
我想要注入bean的JUnit类:
package somepackage;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@ContextConfiguration("classpath*:applicationContext-test.xml")
public class SomeBeanTest {
@Autowired
ApplicationContext ctx;
@Autowired
@Value("1")
private SomeBean someBean;
private SomeBean someBean2;
@Before
public void setUp() throws Exception { …Run Code Online (Sandbox Code Playgroud) 基于此答案,我尝试使用java.util.Function接口配置请求范围Bean 。
我的配置如下所示:
@Configuration
public class RequestConfig {
@Bean
public Function<? extends BaseRequest, RequestWrapper<? extends BaseRequest, ? extends BaseResponse>> requestWrapperFactory() {
return request -> requestWrapper(request);
}
@Bean
@RequestScope
public RequestWrapper<? extends BaseRequest, ? extends BaseResponse> requestWrapper(
BaseRequest request) {
RequestWrapper<?, ?> requestWrapper = new RequestWrapper<BaseRequest, BaseResponse>(request);
return requestWrapper;
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试像这样使用bean:
@RestController
public class CheckRequestController {
private final RequestService<CheckRequest, CheckResponse> checkRequestServiceImpl;
@Autowired
private Function<CheckRequest, RequestWrapper<CheckRequest, CheckResponse>> requestWrapperFactory;
public CheckRequestController(
RequestService<CheckRequest, CheckResponse> checkRequestServiceImpl) {
super();
this.checkRequestServiceImpl = …Run Code Online (Sandbox Code Playgroud)