Ond*_*hal 5 java spring spring-java-config
我将旧的xml/java配置转换为纯java配置.在xml中,我使用参数注入配置文件,如下所示:
<bean class="com.project.SpringRestConfiguration">
<property name="parameters" ref="parameters" />
</bean>
@Configuration
public class SpringRestConfiguration {
private Parameters parameters;
public void setParameters(Parameters parameters) {
this.parameters = parameters;
}
// @Bean definitions
...
}
Run Code Online (Sandbox Code Playgroud)
是否可以在javaconfig中注入参数?(无需使用自动装配!)
@Configuration
@Import(SpringRestConfiguration.class)
Run Code Online (Sandbox Code Playgroud)
编辑:使用@Import,我看不到有任何机会将参数注入SpringRestConfiguration
基本上你需要使用@Autowired,但你仍然可以使用名称而不是像这样输入解释:
@Configuration
public class SpringRestConfiguration {
@Autowired
@Qualifier("parameters") // Somewhere in your context you should have a bean named 'parameters'. It doesn't matter if it was defined with XML, configuration class or with auto scanning. As long as such bean with the right type and name exists, you should be good.
private Parameters parameters;
// @Bean definitions
...
}
Run Code Online (Sandbox Code Playgroud)
这解决了您在使用时提到的混淆问题@Autowired——这里不存在注入哪个bean的问题,即名为 的bean parameters。
您甚至可以做一些测试,parameters像以前一样保留 XML 中定义的 bean,使用@Autowired,看看它是否有效。然后才迁移parameters到@Configuration课堂。
在我的回答中,您可以找到有关如何逐步迁移 XML 的完整说明@Configuration。
您还可以完全跳过私有成员并执行如下操作:
@Configuration
public class SpringRestConfiguration {
@Bean
public BeanThatNeedsParamters beanThatNeedsParamters (@Qualifier("parameters") Parameters parameters) {
return new BeanThatNeedsParamters(parameters)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1424 次 |
| 最近记录: |